是否可以在T-SQL中编写反映此伪代码的正确查询:
SELECT {primary_key}, {column_name}
FROM {table}
WHERE {any column_name value} is NULL
即。没有明确引用每个列名。
听起来很简单,但我搜索得非常广泛而且一无所获。
答案 0 :(得分:2)
您必须使用动态SQL来解决该问题。我已经演示了如何做到这一点。 使用此sql,您可以选择一个表并检查id为1的行,以确保列为null和主键。我在脚本的底部包含了一个测试表。如果没有主键且没有列为空,则代码不会显示任何内容。
DECLARE @table_name VARCHAR(20)
DECLARE @chosencolumn VARCHAR(20)
DECLARE @sqlstring VARCHAR(MAX)
DECLARE @sqlstring2 varchar(100)
DECLARE @text VARCHAR(8000)
DECLARE @t TABLE (col1 VARCHAR(30), dummy INT)
SET @table_name = 'test_table' -- replace with your tablename if you want
SET @chosencolumn = 'ID=1' -- replace with criteria for selected row
SELECT @sqlstring = COALESCE(@sqlstring, '') + 'UNION ALL SELECT '',''''NULL '''' '' + '''+t1.column_name+''', 1000 ordinal_position FROM ['+@table_name+'] WHERE [' +t1.column_name+ '] is null and ' +@chosencolumn+ ' '
FROM INFORMATION_SCHEMA.COLUMNS t1
LEFT JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE t2
ON t1.column_name = t2.column_name
AND t1.table_name = t2.table_name
AND t1.table_schema = t2.table_schema
WHERE t1.table_name = @table_name
AND t2.column_name is null
SET @sqlstring = stuff('UNION ALL SELECT '',''''PRIMARY KEY'''' ''+ column_name + '' '' col1, ordinal_position
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE table_name = ''' + @table_name+ '''' + @sqlstring, 1, 10, '') + 'order by 2'
INSERT @t
EXEC( @sqlstring)
SELECT @text = COALESCE(@text, '') + col1
FROM @t
SET @sqlstring2 ='select '+stuff(@text,1,1,'')
EXEC( @sqlstring2)
结果:
id host_id date col1
PRIMARY KEY PRIMARY KEY PRIMARY KEY NULL
测试表
CREATE TABLE [dbo].[test_table](
[id] int not null,
[host_id] [int] NOT NULL,
[date] [datetime] NOT NULL,
[col1] [varchar](20) NULL,
[col2] [varchar](20) NULL,
CONSTRAINT [PK_test_table] PRIMARY KEY CLUSTERED
(
[id] ASC,
[host_id] ASC,
[date] ASC
))
测试数据
INSERT test_table VALUES (1, 1, getdate(), null, 'somevalue')