与 NULL 值连接(不应替换 NULL)

Rac*_*SQL 0 null sql-server sql-server-2008-r2 string-manipulation

经过一段时间寻找答案后,我收到了很多问题,说要使用coalesceconcat()等,但我需要的是:

桌子:

create table nulos ( nome varchar(max))
alter table nulos add cidade varchar(max)
Run Code Online (Sandbox Code Playgroud)

价值观:

insert into nulos values ( 'rafael','são paulo'),('juliana',null)
Run Code Online (Sandbox Code Playgroud)

我需要将这个表中的值连接到一个插入中,如下所示:

 select 'insert into nulos (nome,cidade) values ('+nome+','+cidade+')'
from nulos
Run Code Online (Sandbox Code Playgroud)

和选择的结果:

insert into nulos (nome,cidade) values (rafael,são paulo)
NULL
Run Code Online (Sandbox Code Playgroud)

如何在此串联中使用 NULL 值?每个答案都说用''or替换空值'_',但我需要的是:

insert into nulos (nome,cidade) values (rafael,são paulo)

insert into nulos (nome,cidade) values (Juliana,NULL)
Run Code Online (Sandbox Code Playgroud)

SET CONCAT_NULL_YIELDS_NULL on 不是一个选项,因为它只是删除 NULL 值,我需要插入它。

ind*_*iri 6

将您的字符串用单引号括起来,以便将它们作为字符串输入。NULL 不需要引号。

SELECT 'INSERT INTO nulos (nome,cidade) VALUES (' +
    CASE WHEN nome is null then 'NULL' ELSE ''''+
        REPLACE(nome,'''','''''')+'''' END + 
    ',' +
    CASE WHEN cidade is null then 'NULL' ELSE ''''+
        REPLACE(cidade,'''','''''')+'''' END +
    ')'
FROM nulos
Run Code Online (Sandbox Code Playgroud)

这会给你:

INSERT INTO nulos (nome,cidade) VALUES ('rafael','são paulo')
INSERT INTO nulos (nome,cidade) VALUES ('Juliana',NULL)
Run Code Online (Sandbox Code Playgroud)

  • @RacerSQL 只要你的名字都不是`O'Brien` 或 [Robert'); DROP TABLE 学生;--](http://bobby-tables.com) (4认同)