sqldatabaseselectnullablesqldb

Generate a script out of nullable column in SQL table


Following is my query:

SELECT 'INSERT INTO MyTable (
CancellationReason
)
VALUES ( 
''' + rc.CancelReason  + '''
)'
FROM AnotherTable a

I get below result:

enter image description here

Since the column a.CancelReason is nullable, you see NULL values in the result set. But I need the result something like this (I need a string representation in place of NULL (basically an insert statement in the current example)):

enter image description here

I tried something like this but no help:

SELECT 'INSERT INTO MyTable (
CancellationReason
)
VALUES ( 
''' + ISNULL(a.CancelReason, null)  + '''
)'
FROM AnotherTable a

Could you please suggest?


Solution

  • You can query like this w/o using CASE condition:

    SELECT 'INSERT INTO MyTable (CancellationReason) VALUES (' + COALESCE('''' + CancelReason + '''','NULL')  + ')'
    FROM AnotherTable a
    

    or you can use direct INSERT INTO...SELECT statement as suggested by @Tim