仅选择具有空值的列

2022-06-20 00:00:00 sql-server
如何选择表中仅包含所有行的空值的所有列?我使用的是MS SQL Server 2005。我正在尝试找出表中未使用的列,以便删除它们。


解决方案

以下是SQL2005或更高版本:将ADDR_ADDRESS替换为您的表名称。

declare @col varchar(255), @cmd varchar(max)

DECLARE getinfo cursor for
SELECT c.name FROM sys.tables t JOIN sys.columns c ON t.Object_ID = c.Object_ID
WHERE t.Name = 'ADDR_Address'

OPEN getinfo

FETCH NEXT FROM getinfo into @col

WHILE @@FETCH_STATUS = 0
BEGIN
    SELECT @cmd = 'IF NOT EXISTS (SELECT top 1 * FROM ADDR_Address WHERE [' + @col + '] IS NOT NULL) BEGIN print ''' + @col + ''' end'
    EXEC(@cmd)

    FETCH NEXT FROM getinfo into @col
END

CLOSE getinfo
DEALLOCATE getinfo

相关文章