在我的桌子上table1有 6 列位置,a、b、c、d、e。
Locations [a] [b] [c] [d] [e]
[1] 10.00 Null Null 20.00 Null
[2] Null 30.00 Null Null Null
我需要这样的结果
Locations [a] [b] [d]
[1] 10.00 Null 20.00
[2] Null 30.00 Null
我的问题是如何使用 sql 查询检测和删除包含所有空值的列。
是否可以?
如果是,请帮忙并提供样品。
这是一个快速(且丑陋)的存储过程,它获取表的名称并打印(或者如果需要的话删除)充满空值的字段。
ALTER procedure mysp_DropEmptyColumns
@tableName nvarchar(max)
as begin
declare @FieldName nvarchar(max)
declare @SQL nvarchar(max)
declare @CountDef nvarchar(max)
declare @FieldCount int
declare fieldNames cursor local fast_forward for
select c.name
from syscolumns c
inner join sysobjects o on c.id=o.id
where o.xtype='U'
and o.Name=@tableName
open fieldNames
fetch next from fieldNames into @FieldName
while (@@fetch_status=0)
begin
set @SQL=N'select @Count=count(*) from "'+@TableName+'" where "'+@FieldName+'" is not null'
SET @CountDef = N'@Count int output';
exec sp_executeSQL @SQL, @CountDef, @Count = @FieldCount output
if (@FieldCount=0)
begin
set @SQL = 'alter table '+@TableName+' drop column '+@FieldName
/* exec sp_executeSQL @SQL */
print @SQL
end
fetch next from fieldNames into @FieldName
end
close fieldNames
end
这使用光标,有点慢且复杂,但我怀疑这是您经常运行的一种过程
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)