-2

我有多个表中具有相同名称的多个列, table_1有列Xtable_2有列x等等。如何从没有联合的所有表中选择查询X列。如果使用联合,我必须在查询语句上写下每个表名,我不这样做。我想做:

Select X from (All table with containing X) where X value (not X name) = 'ABC'.

我使用微软 SQL。可能吗 ?谢谢

4

2 回答 2

1

您可以使用动态 SQL 执行此操作并以这种方式构建查询:

declare @sql as nvarchar(max) = N''
declare @columnname as nvarchar(100) = N'X'
declare @columnvalue as nvarchar(100) = N'ABC'

select @sql = @sql + N' UNION ALL SELECT ' + QUOTENAME(c.name) + N' FROM '
    + QUOTENAME(s.name) + N'.'
    + QUOTENAME(t.name)
    + N' WHERE ' + QUOTENAME(c.name) + N' = ''' + @columnvalue +  ''''
from sys.columns c
inner join sys.tables t on c.object_id = t.object_id
inner join sys.schemas s on t.schema_id = s.schema_id
where c.name = @columnname

set @sql = STUFF(@sql, 1, 10, N'')

exec sp_executesql @sql
于 2014-03-20T04:12:21.430 回答
-2

试试下面对你有用的。

   Select a.x,b.x
   from table_name a,table_name1 b
   where a.x = b.x
   and a.x = 'ABC';
于 2014-03-20T04:12:14.167 回答