T-SQL 如何计算每列的记录数
我有一个包含超过 120 列的表,需要确定哪一列使用最少。我尝试使用 sql 查询来执行此操作,但发现 T-SQL 更简单一些。
我尝试了以下操作,但每列的计数结果均为 0。
Declare data1 Cursor for select column_name
from information_schema.columns
where table_name = 'repository'
Declare @mField nvarchar(255)
Declare @count int
Open data1;
fetch next from data1 into @mField;
set @count = -1;
while @@fetch_status = 0
begin
select @count = count(@mField)
from repository where tablereference =
'central' and ( @mField!= null )
print @mField+' ' ;
print @count;
Fetch next from data1 into @mField;
end
close data1;
deallocate data1;
I have a table with over 120 columns and need to determine which column is used the least. I tried using sql queries to do this, but found T-SQL a bit simpler.
I tried the following but my count comes out as 0 for every column.
Declare data1 Cursor for select column_name
from information_schema.columns
where table_name = 'repository'
Declare @mField nvarchar(255)
Declare @count int
Open data1;
fetch next from data1 into @mField;
set @count = -1;
while @@fetch_status = 0
begin
select @count = count(@mField)
from repository where tablereference =
'central' and ( @mField!= null )
print @mField+' ' ;
print @count;
Fetch next from data1 into @mField;
end
close data1;
deallocate data1;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不能对这样的值进行计数,因为您只是测试 @mField 是否为 NULL。列名称未被替换。
无论如何,COUNT 都会忽略 NULL,因此如果您想计算非空值,请执行以下操作:
这会为所有列查询表一次
You can't count values like this because you are only testing if @mField is NULL. The column name isn't substituted.
COUNT ignores NULLs anyway so if you want to count non-null values, do this:
This queries the table once for all columns
您需要在中间使用一些动态sql来实现您的目标。
You need to use some dynamic sql in the middle to acheive your aim here.
您的
count(@mField)
是@mField
中恰好出现的文字值的计数,它不会将字段名称解析为 < code>COUNT(fldBlah),您需要为此使用动态 SQL。对于类似的输出;
tablereference
列中有 5 个非空值等Your
count(@mField)
is a count of the litteral value that happens to be in@mField
, its not resolving the field name intoCOUNT(fldBlah)
, you would need to use dynamic SQL for that.For an output like;
Where there are 5 non-null values in column
tablereference
etc您需要使用
IS NOT NULL
而不是!= NULL
You need to use
IS NOT NULL
instead of!= NULL