如何使用插入创建表以使列可以为空?

发布于 2024-12-06 14:51:14 字数 513 浏览 0 评论 0原文

使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

呆° 2024-12-13 14:51:14

将其放入计算表达式中,因为通常这些表达式会被视为 NULL ,除非包含在 ISNULL()

WITH    cte ( a )
        AS ( SELECT   CAST(1 AS INT)
        UNION ALL
        SELECT   2
            )
SELECT * INTO a_tmp FROM cte

Make it into a computed expression as generally these get treated as NULL-able unless wrapped in ISNULL()

WITH    cte ( a )
        AS ( SELECT   CAST(1 AS INT)
        UNION ALL
        SELECT   2
            )
SELECT * INTO a_tmp FROM cte
久伴你 2024-12-13 14:51:14

如果您想在表中显式定义字段可为空,正确的方法是使用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)...)

似梦非梦 2024-12-13 14:51:14

当您使用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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文