唯一可行的方法是使用动态 SQL:
declare @stmt nvarchar(max), @value nvarchar(max)
select @stmt = isnull(@stmt + ' union all ', '') + '
select ''' + TABLE_NAME + ''', count(*) from ' + TABLE_NAME + ' where my_column = @value'
from INFORMATION_SCHEMA.COLUMNS
where COLUMN_NAME = 'my_column'
select @value = '12345'
exec sp_executesql
@stmt = @stmt,
@params = N'@value nvarchar(max)',
@value = @value
更新:
对于 SQL 2000,你可以使用nvarchar(4000)
如果你有大量的表,你可以使用临时表 + 游标:
create table #Temp_Results (table_name nvarchar(128), cnt int)
declare @stmt nvarchar(4000), @value nvarchar(128)
declare t_cursor cursor local fast_forward for
select
'select ''' + TABLE_NAME + ''', count(*) from ' + TABLE_NAME + ' where id = @value'
from INFORMATION_SCHEMA.COLUMNS
where COLUMN_NAME = 'name'
select @value = 1
open t_cursor
fetch t_cursor into @stmt
while @@fetch_status = 0
begin
insert into #Temp_Results
exec sp_executesql
@stmt = @stmt,
@params = N'@value nvarchar(128)',
@value = @value
fetch t_cursor into @stmt
end
close t_cursor
deallocate t_cursor
select * from #Temp_Results