您的示例中的表名无法像属性一样访问。它只是一个字符串,而不是表本身。我已经包含了一个可能对你有用的解决方案。感觉有点像黑客,但它会让你上路。
DECLARE @Value INT, @Column_Name VARCHAR(MAX)
SELECT @Value = 4, @Column_Name = 'ProgramId'
IF OBJECT_ID(N'tempdb..#Results',N'U') IS NOT NULL
DROP TABLE #Results
SELECT '[' + SCHEMA_NAME(t.schema_id) + '].[' + t.name + ']' AS fulltable_name, SCHEMA_NAME(t.schema_id) AS schema_name, t.name AS table_name,
i.rows [Row_Count]
INTO #Results
FROM sys.tables AS t INNER JOIN
sys.sysindexes AS i ON t.object_id = i.id AND i.indid < 2
INNER JOIN information_schema.COLUMNS C ON t.name = c.TABLE_NAME AND SCHEMA_NAME(t.schema_id)= c.TABLE_SCHEMA
WHERE C.COLUMN_NAME = @Column_Name
DECLARE @SQL VARCHAR(MAX)
SELECT @SqL = COALESCE(@SqL +' UNION ',' ') + 'SELECT '''+ fulltable_name + ''', COUNT(*) FROM ' + fulltable_name + ' where ' + @Column_Name + ' = ' + CAST(@Value AS VARCHAR(1000))+ ' GROUP BY ' + @Column_Name + ' '
FROM #Results
PRINT(@SqL)
EXEC (@SqL)
IF OBJECT_ID(N'tempdb..#Results',N'U') IS NOT NULL
DROP TABLE #Results