SQL query – Get the number of non-null entries in all table columns without typing in each column names

DECLARE
@col varchar(255),
@cmd varchar(max), 
@numval varchar(max), 
@Parm varchar(500),
@SQLString nvarchar(500),
@ParmDefinition nvarchar(500),
@CountSQLQuery varchar(30);

DECLARE getinfo cursor for SELECT c.name FROM sys.tables t JOIN sys.columns c ON
t.Object_ID = c.Object_ID WHERE t.Name = 'YOUR_TABLE_NAME' 
OPEN getinfo 
FETCH NEXT FROM getinfo into @col 
WHILE @@FETCH_STATUS = 0
BEGIN
      SET @SQLString = N'SELECT @result = COUNT(*) FROM YOUR_TABLE_NAME where ' + @col  + ' is not null';
      SET @ParmDefinition = N'@result varchar(30) OUTPUT';
      EXECUTE sp_executesql @SQLString, @ParmDefinition, @result=@CountSQLQuery OUTPUT;
      print @col + '    ' + @CountSQLQuery

FETCH NEXT FROM getinfo into @col
END 
CLOSE getinfo DEALLOCATE getinfo

Comments

Popular posts from this blog

Metastorm - Open form in an action from a list or link

Corporate Intranet Information Architecture – a Publishing Site

No Search Results in SharePoint Contextual Search OSSSearchResults.aspx