For a given table, I need an SQL (SQL Server 2008 Query) which can get all the column names having column value as NULL.
-
Column names are null? I assume you want to return all columns where the records are null?Darren– Darren2012-10-12 07:33:51 +00:00Commented Oct 12, 2012 at 7:33
-
2should any value of the column or all values of the column be null?Joe G Joseph– Joe G Joseph2012-10-12 07:46:26 +00:00Commented Oct 12, 2012 at 7:46
-
2Or another alternative is that you want to know all of the columns which can accept nulls. You need to edit your question and be more clear on what you're actually trying to find.Damien_The_Unbeliever– Damien_The_Unbeliever2012-10-12 09:54:00 +00:00Commented Oct 12, 2012 at 9:54
1 Answer
Following should work, it is filtered by database, schema and table. It retrieves column name when a NULL value exists in any row of a column (but that's just a minor consideration that you can play with and set it any way you want in a query contained in an @sql variable by changing EXISTS/NOT EXISTS conditions):
DECLARE @dbname VARCHAR(100) = 'yourDB'
DECLARE @schemaName VARCHAR(100) = 'yourSchema'
DECLARE @tableName VARCHAR(100) = 'yourTable'
DECLARE @result TABLE (col VARCHAR(4000))
SELECT @dbname dbname
,t.name tbl
,c.name col
INTO #temp
FROM sys.columns c
JOIN sys.tables t ON
t.object_id = c.object_id
WHERE c.is_nullable = 1
AND t.name = @tableName
DECLARE @sql NVARCHAR(MAX) =
STUFF(
(
SELECT 'UNION ALL SELECT CASE WHEN EXISTS (SELECT 1 FROM ' + @dbname + '.' + @schemaName + '.' + tbl + ' WHERE ' + col + ' IS NULL) THEN '''+ @schemaName + '.' + tbl + '.' + col+''' END AS NULL_Value_Exists '
FROM #temp
FOR XML PATH('')
), 1, 10, ' ')
INSERT @result
EXEC(@sql)
SELECT *
FROM @result
WHERE col IS NOT NULL
DROP TABLE #temp
If you would like to get all the columns of all tables from a certain schema that satisfy given conditions you wouldn't even have to specify table name and you would simply join sys.schemas. That would give you a list of all columns from all tables on a specified schema that contain NULL in any row, only thing required would be to change the first query into:
SELECT @dbname dbname
,t.name tbl
,c.name col
INTO #temp
FROM sys.columns c
JOIN sys.tables t ON
t.object_id = c.object_id
JOIN sys.schemas s ON
s.schema_id = t.schema_id
WHERE c.is_nullable = 1
AND s.name =@schemaName