What is the syntax error ?
Before you print @nullcnt
, you need to assign a value to this variable first, while you didn't.
Try this:
set @sql='select @nullcnt=count(1) from ' + QUOTENAME(@schemaName) + '.' + QUOTENAME(@tableName) + ' where ' + QUOTENAME(@columnName) + ' is null '
EXECUTE [sys].[sp_executesql] @sql,N'@nullcnt int OUTPUT',@nullcnt = @nullcnt OUTPUT;
SELECT TABLE_SCHEMA=@schemaName
,TABLE_NAME=@tableName
,COLUMN_NAME=@columnName
,nullcnt=@nullcnt
SET @t1=@t1+1
END
SET @i=@i+1
END
Also, you could try this query using STRING_AGG which is supported by SQL Server 2017 (14.x) and later.
DECLARE @sql nvarchar(max) =
(
SELECT STRING_AGG(TableQuery, N'
UNION ALL
')
FROM (
SELECT N'
SELECT
TableName,
Col as ColumnName,
TotalRows,
NonNullRows,
NullsRows = TotalRows - NonNullRows
FROM (SELECT
TableName = ' + QUOTENAME(t.name, '''') + N',
TotalRows = COUNT(*),
' + STRING_AGG(CAST(QUOTENAME(c.name) + ' = COUNT(' + QUOTENAME(c.name) + ')' AS nvarchar(max)), ',') + N' FROM ' + QUOTENAME(SCHEMA_NAME(t.schema_id)) + '.' + QUOTENAME(t.name) + N')t
UNPIVOT (NonNullRows FOR Col IN (
' + STRING_AGG(CAST(QUOTENAME(c.name) AS nvarchar(max)), ',') + N'
)) p'
FROM sys.tables t JOIN sys.columns c ON c.object_id = t.object_id
-- WHERE filter
GROUP BY t.object_id, t.name, t.schema_id
) AS t(TableQuery));
--PRINT @sql; -- for testing
EXEC sp_executesql @sql;
Best regards,
Cosmog Hong
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.