假设我有一个表,其中包含其他表的列表
Declare @MyList varchar(max)
@MyList = Select tablename from ListofTables
它带回了50个表名的列表
如何在单个select语句中使用该表名列表?我在想一个for循环或者其他什么东西?
For each tablename in @MyList
Select * from tablename
您可以尝试下一种方法:
-- Table
CREATE TABLE #ListOfTables (
[TableName] varchar(max)
)
INSERT INTO #ListOfTables
([TableName])
VALUES
('Table1'),
('Table2'),
('Table3'),
('Table4'),
('Table5'),
('Table6'),
('Table7'),
('Table8'),
('Table9')
-- Statement
DECLARE @stm nvarchar(max)
SET @stm = N''
SELECT @stm = @stm + N'SELECT * FROM ' + QUOTENAME([TableName]) + N'; '
FROM #ListOfTables
/*
-- Or using FOR XML PATH
SELECT @stm = (
SELECT CONCAT(N'SELECT * FROM ', QUOTENAME([TableName]), N'; ')
FROM #ListOfTables
FOR XML PATH('')
)
*/
PRINT @stm
EXEC sp_executesql @stm