Try this by replacing two occurrences of "Directory" with the name of your table. This was successfully tested in SQL Server 2008 R2 Dev Edition in the default ReportServer database.
DECLARE @Sql nvarchar(max) SET @Sql = 'SELECT 0' SELECT @Sql = @Sql + ' + CASE WHEN [' + [sys].[columns].[name] + '] IS NULL THEN 1 ELSE 0 END' FROM [sys].[columns] WHERE [sys].[columns].[object_id] = OBJECT_ID('Catalog') AND [sys].[columns].is_nullable = 1 SET @Sql = @Sql + ' AS [NullValuesCount] FROM [Catalog]' PRINT @Sql EXEC sp_executesql @Sql
Note that this approach is susceptible to SQL-Injection attacks if you cannot trust the source of column names (for example, if end users can create columns with names under their control).
source share