如果我有以下表格:
PLAYERS
ID Name
== ===========
1 Mick
2 Matt
教练员
ID Name
== ===========
1 Bill
2 Don
我在下面有一个脚本来查找所有包含名为“Name”的列的表:
SELECT t.name AS table_name FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE 'Name'
返回以下内容:
table_name
===========
PLAYERS
COACHES
如何从上面的查询返回的两个表中选择所有行?
答案 0 :(得分:9)
你必须使用动态sql,尝试这样的事情:
declare @t table( tablename varchar(50))
declare @sql varchar(max)
set @sql = ''
insert into @t
SELECT t.name AS table_name FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE 'Name'
select @sql = @sql + 'Select * From ' + tablename + ' union ' from @t
--remove the trailing 'union'
Select @sql = substring(@sql, 1, len(@sql) - 6)
exec (@sql)
以上脚本创建并执行以下sql
select * from coaches
union
select * from players
由于我们在此处使用union
,因此将name
作为列的所有表格具有相同的结构非常重要。
答案 1 :(得分:-2)
SELECT p.Id,p.Name,c.Id,c.Name
FROM Players p JOIN Coaches c
ON p.Id=c.Id
可能这可以帮到你。