2

For a given table, I need an SQL (SQL Server 2008 Query) which can get all the column names having column value as NULL.

3
  • Column names are null? I assume you want to return all columns where the records are null? Commented Oct 12, 2012 at 7:33
  • 2
    should any value of the column or all values of the column be null? Commented Oct 12, 2012 at 7:46
  • 2
    Or 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. Commented Oct 12, 2012 at 9:54

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Great, you're welcome, if you find the answer most useful you can mark it as correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.