如何删除SQL Server 2008 R2中所有行只有一个值的多个列

时间:2013-11-16 22:00:45

标签: sql sql-server sql-server-2008-r2

我在SQL Server 2008 R2中有一个大表,它包含许多列和数百万行。

有些列的所有行都具有相同的值。

例如

col1 col2 col3  col4 col5.....
a     b    c     1    null
a     d    e     1    null
a     f    g     1    null
a     h    I     1    null

我想删除那些列,例如col1,col4,col5以及更多列。

我知道drop column,我想我只是不知道如何在这些情况下选择多个列

在这种情况下我该怎么办?

非常感谢

1 个答案:

答案 0 :(得分:4)

您可以在一个语句中指定多个列:

alter table 
    mytable
drop column
    col4, col5

要查看给定列的值,您可以使用count distinct

Select
    count(distinct col1),
    count(distinct col2),
    count(distinct col3),
    ...
from
    mytable

以下是如何动态构建先前查询的大纲:

Declare 
    @sql nvarchar(max) = N'select',
    @tab sysname = 'mytable', -- replace with table name
    @col sysname,
    @sep nvarchar(1)

Declare col_cursor cursor local fast_forward for
select
    name
from
    sys.columns
where
    object_id = object_id(@tab)

open col_cursor

fetch next from col_cursor into @col

while @@fetch_status = 0
begin
    set @sql += @sep + N' count(distinct ' + quotename(@col) + N') as ' 
        + quotename(@col)
    set @sep = N','
    fetch next from col_cursor into @col
end

close col_cursor
deallocate col_cursor

set @sql += ' from ' + quotename(@tab)

exec sp_executesql @sql