[英]Select all from tables where table names are from another table in SQL
我有一个临时表,它有一个 TableName 列。 我想遍历临时表并选择表中的所有内容(其中 table 是临时表中的 TableName 列)。
我一直在浏览以下链接和相关链接,但是我无法根据我的需要进行调整。 任何帮助是极大的赞赏。
我正在使用 SQL Server 2014
我尝试过的东西
声明@id int WHILE EXISTS(SELECT * FROM ##tt_tableList) BEGIN 从##tt_tableList 中选择Top 1 @id = Id
-- Do the work --
declare @query nvarchar(max)
set @query = 'Select * from (select TableName from ##tt_tablelist where id = '' +Cast(@id as nvarchar(50))+'')'
select @query
declare @tableName nvarchar(50)
set @tableName = (select TableName from ##tt_tableList where id = @id)
select @tableName
execute(@query)
-- Scrap the ID and Move On --
Delete ##tt_tableList where ID = @id
END
如果我理解正确的话,这就是你所要求的:
DECLARE @tbl table (TableName varchar(50))
insert into @tbl values ('SomeTableName')
insert into @tbl values ('AnotherTableName')
DECLARE @Tables VARCHAR(8000)
SELECT @Tables = COALESCE(@Tables + CHAR(13), '') + 'SELECT * FROM '+ TableName
FROM @tbl
exec(@Tables)
只需在@tbl 中插入您的表名
我根据我们的一位堆栈溢出者的回答尝试了这个,并且它有效。
DECLARE @Tables VARCHAR(8000)
SELECT @Tables = COALESCE(@Tables + CHAR(13), '') + 'SELECT * FROM '+ TableName + ' Where Event like ''%CM_Manual_Change%'''
FROM ##tt_tableList
select @Tables
exec(@Tables)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.