复制SQL Server中任何列中至少有一个空值的行
我有表_1,它有一些列。我想将该数据复制到表2,该表在表1的任何列中至少有一个空值。例如,表1有三列。现在,我想将这些行复制到表2,该表在表1的三列中至少有一个空值 我使用以下查询进行了尝试:复制SQL Server中任何列中至少有一个空值的行,sql,sql-server,tsql,sql-server-2017,Sql,Sql Server,Tsql,Sql Server 2017,我有表_1,它有一些列。我想将该数据复制到表2,该表在表1的任何列中至少有一个空值。例如,表1有三列。现在,我想将这些行复制到表2,该表在表1的三列中至少有一个空值 我使用以下查询进行了尝试: insert into table_2 (col1, col2, col3) select col1, col2, col3 from table_1 where col1 is null or col2 is null or col3 is null 但是,表2有一个问题,即表2中有一列“error\
insert into table_2 (col1, col2, col3)
select col1, col2, col3
from table_1
where col1 is null or col2 is null or col3 is null
但是,表2有一个问题,即表2中有一列“error\u value”,该列应包含指示哪些列对应于该特定行具有NULL值的数据,就像如果该行中的col2缺少值,表2应该提到“col2为NULL”。如果有多个列具有空值,则应提及“error_value”列中的所有列,如“col1,col2,col3”,如果所有列都缺少值,则为空
任何建议或帮助我如何实现它。使用
CASE
表达式获取空列,然后连接。从SQL Server 2017开始,最好使用CONCAT_WS
()实现这一点
更新
2017版推出了
concat_ws
,可以显著简化代码-请查看。
我将这个答案留在这里,希望它能帮助其他使用旧版本SQL Server的读者
第一版一个简单的解决方案是结合使用
case
,concat
,stuff
,以及字符串连接操作符(+
),利用concat
将隐式地将null
转换为空字符串,而+
将不转换为空字符串的事实
首先,创建并填充样本表(请在以后的问题中保存此步骤):
然后,insert…select语句:
insert into table_2 (col1, col2, col3, error_value)
select
col1, col2, col3, stuff(
concat(
',' + case when col1 is null then 'col1' end, -- will be null if col1 contains a value
',' + case when col2 is null then 'col2' end, -- will be null if col2 contains a value
',' + case when col3 is null then 'col3' end, -- will be null if col3 contains a value
' is null'), 1, 1, '')
from table_1
where col1 is null or col2 is null or col3 is null
请参见上的现场演示,使用CONCAT和IIF进行以下查询如何:
insert into
table_2 (col1, col2, col3, col4)
select
col1,
col2,
col3,
CONCAT(
IIF(col1 is null, 'col1 ', ''),
IIF(col2 is null, 'col2 ', ''),
IIF(col3 is null, 'col3 ', ''),
' is null'
)
from
table_1
where
col1 is null
or col2 is null
or col3 is null
尝试使用简单的案例陈述和concat
INSERT INTO #table_2 (col1, col2, col3,error_value)
SELECT col1, col2, col3
,SUBSTRING(CONCAT( CASE WHEN col1 IS NULL THEN ',col1' ELSE '' END
,CASE WHEN col2 IS NULL THEN ',col2' ELSE '' END
,CASE WHEN col3 IS NULL THEN ',col3' ELSE '' END
),2,20) + ' is null'
FROM #table_1
WHERE col1 IS NULL OR col2 IS NULL OR col3 IS NULL
请提供示例数据+预期结果。因此,col1
到col3
中的数据在源污迹目标表之间应该相同,对吗?它只是一个过滤视图,包含丢失数据的记录子集,并包含一个新列,总结丢失的数据。正确吗?您能否提供一些示例,说明在{1,2,3}缺少值的情况下,error_value
消息应该是什么样子的?@JeremyCaney,当所有列都缺少值时,它应该指示“col1,col2,col3为null”。您使用的SQL Server版本是什么?是的,2017年,这是一个比我的答案更好的选择+1.
insert into
table_2 (col1, col2, col3, col4)
select
col1,
col2,
col3,
CONCAT(
IIF(col1 is null, 'col1 ', ''),
IIF(col2 is null, 'col2 ', ''),
IIF(col3 is null, 'col3 ', ''),
' is null'
)
from
table_1
where
col1 is null
or col2 is null
or col3 is null
INSERT INTO #table_2 (col1, col2, col3,error_value)
SELECT col1, col2, col3
,SUBSTRING(CONCAT( CASE WHEN col1 IS NULL THEN ',col1' ELSE '' END
,CASE WHEN col2 IS NULL THEN ',col2' ELSE '' END
,CASE WHEN col3 IS NULL THEN ',col3' ELSE '' END
),2,20) + ' is null'
FROM #table_1
WHERE col1 IS NULL OR col2 IS NULL OR col3 IS NULL