2

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?

2
  • Please update the tags in your question with the RDBMS you are using (postgres, mysql, sql server, snowflake, db2, etc). Likely you just need ISNULL(a.CancelReason, 'null') (notice that null is a string-literal in this case, not a literal null. Commented Mar 19 at 14:35
  • Shouldn't the target have a key? Commented Mar 19 at 15:06

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Hi Harsh, thanks for the reply. This seems to be simple one :) Thank you again!
Happy to help you @RaghavendraHG :)
1

Use an outer CASE expression to decide whether to insert null or a single quoted string:

SELECT 
    CASE WHEN rc.CancelReason IS NOT NULL
         THEN 'INSERT INTO MyTable (CancellationReason) VALUES (''' + rc.CancelReason + ''')'
         ELSE 'INSERT INTO MyTable (CancellationReason) VALUES (NULL)' END
FROM AnotherTable a;

But, more generally, you might have an easier time just executing a direct INSERT INTO...SELECT, along these lines:

INSERT INTO MyTable (CancellationReason)
SELECT CancelReason
FROM SomeOtherTable;

1 Comment

Hi Tim, this helped. Thank you :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.