Create a nullable column using SQL Server SELECT INTO?

This soulution I've recently come up with and though I should share:

select top 0
  B.*
into
  TargetTable
from
  SourceTable as A
    left join SourceTable as B on 1 = 0

This effectively creates a duplicated structure of SourceTable in TargetTable with all columns nullable (at least in sql2008).


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

CONVERT will make your columns nullable, and works for literals/constants too. Tested in SQL Server 2005/2008.

SELECT 
    SomeText = CONVERT(varchar(10), 'literal'),
    SomeNumber = CONVERT(int, 0)
INTO SO5465245

INSERT SO5465245 VALUES (null, null)

SELECT TABLE_NAME, COLUMN_NAME, DATA_TYPE, IS_NULLABLE
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'SO5465245'
ORDER BY TABLE_NAME, ORDINAL_POSITION

DROP TABLE SO5465245