I'm pretty new to Dynamic SQL, and SQL Server in general, but I would like to iterate over a table list within information_schema.tables
. Each iteration has a varchar
variable listing the Month-Year to be searched within the table name (where table_name like concat('USA_RETHHDs_%', @Month)
).
Each table with the matched date would then be placed into a varchar
variable. The problem is, I want to obtain the table
variable from the information_schema.tables
list instead, but am unsure of how this can be done. As a result, I'm trying to go the dynamic route, embedding the varchar
variable into a dynamic SQL query. However, it's expecting a table
variable rather than a varchar
.
declare @Month varchar(6)
declare @Table varchar(32)
declare @sql nvarchar(max)
declare @MonthCount int
while @MonthCount > 0
begin
select @Month = DateSuffix from @DateTable where Row = @MonthCount
select @Table = table_name from information_schema.tables where table_name like concat('USA_RETHHDs_%', @Month)
select @Table = concat('dbo.', @Table)
set @sql = 'select * from @Table'
execute SP_EXECUTESQL @sql
select @MonthCount = @MonthCount - 1
end