简体   繁体   中英

Concat NULL with Varchar SQL Server 2008

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM