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;
You need to use some dynamic sql in the middle to acheive your aim here.
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
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
etcYou need to use
IS NOT NULL
instead of!= NULL