title: T-SQL How To Count Of Records For Each Column
body: <p>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.  </p>
  
  <p>I tried the following but my count comes out as 0 for every column.</p>
  
  <pre><code>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;
  </code></pre>