您的查询不会查询您找到的表。您必须动态构建一个查询来查询您找到的每个表,然后使用union all
.
尝试这个:
declare @Col2Value int = 3
declare @SQL nvarchar(max)
select @SQL =
(
select 'union all '+
'select top(1) '''+t.name+''' as TableName '+
'from '+quotename(t.name)+' '+
'where Column2 = '+cast(@Col2Value as nvarchar(10))+' '
from sys.columns c
inner join sys.tables t
on c.object_id = t.object_id
where c.name = 'Column1'
for xml path(''), type
).value('substring(./text()[1], 11)', 'nvarchar(max)')
exec (@SQL)
上面的代码将构建并执行一个如下所示的查询:
select top(1) 'Table1' as TableName
from [Table1]
where Column2 = 3
union all
select top(1) 'Table2' as TableName
from [Table2]
where Column2 = 3
union all
select top(1) 'Table3' as TableName
from [Table3]
where Column2 = 3
SQL小提琴