Find All Rows With Null Value(s) in Any Column

后端 未结 3 1825
梦毁少年i
梦毁少年i 2020-12-06 00:16

I\'m trying to create a query that will return all the rows that have a null value across all but 1 column. Some rows will have more than one null entry somewhere. There i

3条回答
  •  一向
    一向 (楼主)
    2020-12-06 01:00

    I don't have such a table to test, assuming there is no 'x' as data in any field, I think this should work on Sql-Server; (DEMO)

    NOTE: I have filtered keyColumn as c.name != 'keyColumn'

    DECLARE @S NVARCHAR(max), @Columns VARCHAR(50), @Table VARCHAR(50)
    
    SELECT @Columns = '66', --Number of cols without keyColumn
           @Table = 'myTable'
    
    SELECT @S =  ISNULL(@S+'+ ','') + 'isnull(convert(nvarchar, ' + c.name + '),''x'')'  
    FROM sys.all_columns c 
    WHERE c.object_id = OBJECT_ID(@Table) AND c.name != 'keyColumn'
    
    exec('select * from '+@Table+' where ' + @S + '= replicate(''x'',' + @Columns + ')')
    

提交回复
热议问题