对于视图中的每一行,我需要返回该行的ID列,以及该行中包含NULL的所有列的分隔列表。
所以:
ID | Test1 | Test2 | Test3
5 'a' 'b' NULL
6 'a' 'b' 'c'
7 NULL 'b' NULL
将返回:
ID | InvalidColumns
5 Test3
7 Test1,Test3
我已经看到SO上的解决方案可以告诉你是否有任何列有NULL,或者表中所有行的列是否有NULL,但是没有任何内容列出每行的列。
谢谢!
除了ID列之外,表中的列也是未知的。我需要一个适用于任何具有ID列的表/视图的解决方案。
答案 0 :(得分:1)
您可以像这样使用查询(需要STUFF
才能删除前导逗号
):
SELECT ID,
STUFF(
CONCAT(CASE WHEN Test1 IS NULL THEN ',Test1' END,
CASE WHEN Test2 IS NULL THEN ',Test2' END,
CASE WHEN Test3 IS NULL THEN ',Test3' END
), 1, 1, '') as InvalidColumns
FROM table1 WHERE Test1 IS NULL OR Test2 IS NULL OR Test3 IS NULL;
如果要使查询动态化,请使用以下查询:
DECLARE @table AS NVARCHAR(MAX),
@cols1 AS NVARCHAR(MAX),
@cols2 AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
SET @table = 'Table1'
SET @cols1 = STUFF((SELECT distinct ',CASE WHEN ' + QUOTENAME(c.COLUMN_NAME) + ' IS NULL THEN '',' + c.COLUMN_NAME + ''' END'
FROM INFORMATION_SCHEMA.columns c
WHERE TABLE_SCHEMA = 'dbo' and TABLE_NAME = @table And COLUMN_NAME <> 'Id'
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET @cols2 = STUFF((SELECT distinct 'OR ' + QUOTENAME(c.COLUMN_NAME) + ' IS NULL '
FROM INFORMATION_SCHEMA.columns c
WHERE TABLE_SCHEMA = 'dbo' and TABLE_NAME = @table And COLUMN_NAME <> 'Id'
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,3,'')
SET @query = N'SELECT ID, STUFF(CONCAT(' + @cols1 + '), 1, 1, '''') as InvalidColumns FROM ' + @table + ' WHERE ' + @cols2
--SELECT @cols1, @cols2, @query
EXEC sp_executesql @query
它产生以下结果:
| ID | INVALIDCOLUMNS |
|----|----------------|
| 5 | Test3 |
| 7 | Test1,Test3 |
答案 1 :(得分:0)
如果列已修复,此查询可以提供帮助。
SELECT ID,
CONCAT(case when Test1 is null then 'Test1' end,
case when Test1 is null and (test2 is null or test3 is null) then ',' end,
case when Test2 is null then 'Test2' end,
case when (Test1 is null or test2 is null ) and test3 is null then ',' end,
case when Test3 is null then 'Test3' end
)
as InvalidColumns
FROM table1 WHERE Test1 IS NULL OR Test2 IS NULL OR Test3 IS NULL