When I create a temp table using a select into
in SQL Server, is there a way to specify that a column should be nullable? I have a multi-step process where I'm making a temp table by selecting a lot of columns (which is why I'm not doing a create table #tmp (...)
). After I make that temp table, I'm updating some columns and some of those updates might null out a field.
I know I could do an alter table alter column
statement to achieve what I want, but I'm curious about whether there's a way to specify this in the select
itself. I know you can inline cast
your columns to get the desired datatype, but I can't see how you specify nullability.
Example# When creating tables it is possible to declare a column as nullable or non-nullable. CREATE TABLE MyTable ( MyCol1 INT NOT NULL, -- non-nullable MyCol2 INT NULL -- nullable ) ; By default every column (except those in primary key constraint) is nullable unless we explicitly set NOT NULL constraint.
To set a specific row on a specific column to null use: Update myTable set MyColumn = NULL where Field = Condition. This would set a specific cell to null as the inner question asks.
You can use this query, to set the specific row on a specific column to null this way: Update myTable set MyColumn = NULL where Field = Condition. Here, the above code will set the specific cell to null as per the inner question (i.e. To clear the value from a cell and make it NULL).
Nullability is inherited from the source column.
You can lose or gain nullability with an expression:
Example (constant literals appear to be problematic - need a good NOOP function which can return NULL):
CREATE TABLE SO5465245_IN ( a INT NOT NULL ,b INT NULL ) ; GO SELECT COALESCE(a, NULL) AS a ,ISNULL(b, 0) AS b ,COALESCE(10, NULL) AS c1 ,COALESCE(ABS(10), NULL) AS c2 ,CASE WHEN COALESCE(10, NULL) IS NOT NULL THEN COALESCE(10, NULL) ELSE NULL END AS c3 INTO SO5465245_OUT FROM SO5465245_IN ; GO SELECT TABLE_NAME ,COLUMN_NAME ,IS_NULLABLE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME LIKE 'SO5465245%' ORDER BY TABLE_NAME ,ORDINAL_POSITION ; GO DROP TABLE SO5465245_IN ; GO DROP TABLE SO5465245_OUT ; GO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With