如何使用插入创建表以使列可以为空?
使用 SQL Server 2008。
这是我的问题的一个简化示例:
WITH cte ( a )
AS ( SELECT 1
UNION ALL
SELECT NULL
)
SELECT * INTO a_tmp FROM cte
SELECT * FROM a_tmp
这将创建一个名为 a_tmp
的表,其中包含可为 null 的 int 列。
然而,下一个代码片段将创建具有不可为空列的表:
WITH cte ( a )
AS ( SELECT 1
UNION ALL
SELECT 2
)
SELECT * INTO a_tmp FROM cte
如何更改第二个代码片段以强制创建所有列都可为空的表?
Using SQL Server 2008.
Here is a simplified example of my problem:
WITH cte ( a )
AS ( SELECT 1
UNION ALL
SELECT NULL
)
SELECT * INTO a_tmp FROM cte
SELECT * FROM a_tmp
This creates the table called a_tmp
with a nullable int column.
The next snippet, however creates the table with a non-nullable column:
WITH cte ( a )
AS ( SELECT 1
UNION ALL
SELECT 2
)
SELECT * INTO a_tmp FROM cte
How can I change the second snippet to force the table to be created with all its columns nullable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将其放入计算表达式中,因为通常这些表达式会被视为
NULL
,除非包含在ISNULL()
中Make it into a computed expression as generally these get treated as
NULL
-able unless wrapped inISNULL()
如果您想在表中显式定义字段可为空,正确的方法是使用
CREATE TABLE
。作为一种解决方法,您可以显式地将所有字段转换为其数据类型,但对我来说,这似乎比
CREATE TABLE MyTable (id INT NULL, Otherfield varchar(100)...) 更多工作
If you want to explicitly define a field as nullable in a table, the right way is to use
CREATE TABLE
.As a workaround you can explicitly cast all your fields as their data types, but to me that seems like MORE work than just
CREATE TABLE MyTable (id INT NULL, Otherfield varchar(100)...)
当您使用
SELECT ... INTO
时,任何使用内置函数(例如CAST)的表达式都会被引擎视为可以为NULL。因此,如果您使用
CAST(somecol as int)
,则表达式可为 NULL。When you use
SELECT ... INTO
, any expression that uses a built-in function (e.g. CAST) is considered as NULL-able by the engine.So if you use
CAST(somecol as int)
then the expression is NULLable.