Search code examples
sqlselectsql-server-2014

Select all from tables where table names are from another table in SQL


I have a temp table which has a TableName column. I would like to loop through the temporary table and select everything in the the table (where table is the TableName column in the temp table).

I have been looking through the following link and related links however I am unable to adapt it to my needs. Any help is greatly appreciated.

I am using SQL Server 2014

Something which i have tried

Declare @id int WHILE EXISTS(SELECT * FROM ##tt_tableList) BEGIN Select Top 1 @id = Id from ##tt_tableList

-- 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

Solution

  • If I understood you correctly this is what you are asking for:

    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) 
    

    Just insert your table names in @tbl