Concat NULL with Varchar SQL Server 2008

231 Views Asked by At

I would like to ask how can I concatenate a nvarchar column with NULL without getting NULL? I would like to create an INSERT script using SELECT, but when any of the values is NULL, I get only NULL.

SELECT TOP 10 
    'IF NOT EXISTS(SELECT 1 FROM tblParameterKey 
                   WHERE keyNames='''
        + CAST(ISNULL([keyNames], 'NULL') AS NVARCHAR(255)) + ''')
     BEGIN
         INSERT INTO tblParameterKey VALUES(''' + CAST(ISNULL([keyNames], 'NULL') AS NVARCHAR(255))+''')
     END'
FROM tblParameterKey

This query returns correct insert inly when value is not null. If value is null it returns insert with 'NULL' which is not correct because it will be inserted as varchar and not as null value. If I remove ' ' the whole result will become null.

1

There are 1 best solutions below

4
On BEST ANSWER

Edit - Maybe put the NULLIF statement inside the query string that way it will be null instead of string null.

SELECT TOP 10 
    'IF NOT EXISTS(SELECT 1 FROM tblParameterKey 
                   WHERE keyNames=NULLIF('''
        + [keyNames] + ''', 'NULL') AS NVARCHAR(255))
     BEGIN
         INSERT INTO tblParameterKey VALUES(NULLIF(''' + [keyNames]+''', 'NULL') AS NVARCHAR(255))
     END'
FROM tblParameterKey