How to control nullability in SELECT INTO for literal-based columns

前端 未结 3 748
旧时难觅i
旧时难觅i 2021-01-11 16:57

I am noticing that when I use this statement, the Action column is not nullable:

SELECT TOP 0 SerialNumber, 0 [Action] INTO #MyTable FROM FSE_Se         


        
相关标签:
3条回答
  • 2021-01-11 16:59

    Quick general hint for SELECT ... INTO : use ISNULL( with a column and it will be created as a NOT NULL column in the table.

    0 讨论(0)
  • 2021-01-11 17:20

    It looks like a definitive answer is here. Copying here:

    Metadata is determined based on the source column and expressions used in the SELECT list. Below are the rules:

    1. Any expression that uses a built-in function like SUBSTRING, LEFT, RIGHT etc (except ISNULL) for example is considered as NULLable by the engine. So if you use CAST(somecol as char(8)) then the expression is NULLable

    2. Literals, constants, global variables like @@DBTS, @@ERROR etc are considered non-NULLable since they return some value always

    3. If expression is a column then nullability is derived from the source column metadata

      So to make an expression or column in the SELECT list not null then use ISNULL around the column or expression.

    So, it looks like you are safe to use your CAST expression.

    0 讨论(0)
  • 2021-01-11 17:22

    Personally, for the best control, you should create your table first. For example:

    Create Table #MyTable (
       SerialNumber int Not Null, -- or however this is correctly defined.
       Action int Null
    )
    

    Then, do a Insert Into ... Select From ...

    Insert Into #MyTable(SerialNumber, Action)
    Select SerialNumber, 0
    From FSE_SerialNumber
    

    Then, there will be no question of what the fields should be.

    I know this isn't quite what you asked, but it might be something to consider.

    0 讨论(0)
提交回复
热议问题