我正在尝试修改以下查询以返回特定表中的所有列的列表(不是现在的DB中的所有表),其中字段为null或为空。
据我所知,需要将游标声明更改为指定搜索 表,但需要进行其他更改才能返回空列的名称。
帮助将受到高度赞赏。
declare @tempTable TABLE
(
TableSchema nvarchar(256),
TableName nvarchar(256),
ColumnName sysname,
NotNullCnt bigint
);
declare @sql nvarchar(4000);
declare @tableSchema nvarchar(256);
declare @tableName nvarchar(256);
declare @columnName sysname;
declare @cnt bigint;
declare columnCursor cursor FOR
SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
WHERE IS_NULLABLE = 'YES';
open columnCursor;
fetch next FROM columnCursor INTO @tableSchema, @tableName, @columnName;
while @@FETCH_STATUS = 0
begin
SET @sql = 'select @cnt = COUNT(*) from [' + @tableSchema + '].[' + @tableName +
'] where [' + @columnName + '] is not null';
exec sp_executesql @sql, N'@cnt bigint output', @cnt = @cnt output;
INSERT INTO @tempTable SELECT @tableSchema, @tableName, @columnName, @cnt;
fetch next FROM columnCursor INTO @tableSchema, @tableName, @columnName;
end
close columnCursor;
deallocate columnCursor;
SELECT * FROM @tempTable WHERE NotNullCnt = 0;