Him*_*dri 6 sql sql-server-2005
在我的表table1中有6列Locations,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
Run Code Online (Sandbox Code Playgroud)
我需要像这样的结果
Locations [a] [b] [d]
[1] 10.00 Null 20.00
[2] Null 30.00 Null
Run Code Online (Sandbox Code Playgroud)
我的问题是如何使用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
Run Code Online (Sandbox Code Playgroud)
这使用了一个游标,并且有点慢和令人费解,但我怀疑这是一种你经常运行的程序
如何检测给定列是否只有值NULL:
SELECT 1 -- no GROUP BY therefore use a literal
FROM Locations
HAVING COUNT(a) = 0
AND COUNT(*) > 0;
Run Code Online (Sandbox Code Playgroud)
结果集将由零行(列a没有NULL值)或一行(列a只有NULL值)组成。FWIW 该代码是标准 SQL-92。