in T-SQL, is it possible to find names of columns containing NULL in a given row (without knowing all column names)?
Is it possible in T-SQL to write a proper query reflecting this pseudo-code:
SELECT {primary_key}, {column_name}
FROM {table}
WHERE {any column开发者_如何学运维_name value} is NULL
i.e. without referencing each column-name explicitly.
Sounds simple enough but I've searched pretty extensively and found nothing.
You have to use dynamic sql to solve that problem. I have demonstrated how it could be done. With this sql you can pick a table and check the row with id = 1 for columns being null and primary keys. I included a test table at the bottom of the script. Code will not display anything if there is not primary keys and no columns being 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)
Result:
id host_id date col1
PRIMARY KEY PRIMARY KEY PRIMARY KEY NULL
Test table
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
))
Test data
INSERT test_table VALUES (1, 1, getdate(), null, 'somevalue')
精彩评论