是否有SQL方法可以找出我的架构中哪些列完全充满空值?在我知道的一些表中有一些字段没有被应用程序使用并将被删除,但我想看看是否有一个自动化的方法/脚本在整个数据库中找到它以找到代码审查的候选者/可能被删除。
如果重要,请在x86上运行SQL Server 2005.
提前致谢!
答案 0 :(得分:7)
create table #SuspectColumns (
TABLE_SCHEMA sysname,
TABLE_NAME sysname,
COLUMN_NAME sysname
)
declare csrColumns cursor fast_forward for
select TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS
where IS_NULLABLE = 'YES'
declare @TABLE_SCHEMA sysname,
@TABLE_NAME sysname,
@COLUMN_NAME sysname,
@sql nvarchar(max)
open csrColumns
while (1=1) begin
fetch next
from csrColumns
into @TABLE_SCHEMA, @TABLE_NAME, @COLUMN_NAME
if @@FETCH_STATUS<>0 break
set @sql = N'if not exists(select 1 from ' + QUOTENAME(@TABLE_SCHEMA) + N'.' + QUOTENAME(@TABLE_NAME) + N' where ' + QUOTENAME(@COLUMN_NAME) + N'is not null)
insert into #SuspectColumns values (''' + @TABLE_SCHEMA + N''',''' + @TABLE_NAME + N''',''' + @COLUMN_NAME + N''')'
exec sp_executesql @sql
end /* while */
close csrColumns
deallocate csrColumns
select * from #SuspectColumns
drop table #SuspectColumns
答案 1 :(得分:0)
你可以返回max(列)并检查空值
答案 2 :(得分:0)
在我的头脑中,我相信以下SQL应该可行。它将为每个表/列组合执行查询,如果该表/列组合没有行或所有空行,则查询将返回表名和列名。
DECLARE @table_columns TABLE
(
table_name nvarchar(128),
column_name nvarchar(128)
);
DECLARE @table_name nvarchar(128);
DECLARE @column_name nvarchar(128);
INSERT INTO @table_columns(table_name, column_name)
select TABLE_NAME, COLUMN_NAME from INFORMATION_SCHEMA.columns;
while (select count(*) from @table_columns) > 0
begin
select top 1 @table_name = table_name, @column_name = column_name from @table_columns
exec('SELECT ''' + @table_name + ''' as table_name, ''' + @column_name + ''' as column_name WHERE NOT EXISTS (SELECT TOP 1 * FROM ' + @table_name + ' WHERE ' + @column_name + ' IS NOT NULL)')
delete from @table_columns where table_name = @table_name and column_name = @column_name
end