用varchar替换表变量的动态SQL

时间:2015-07-06 21:21:05

标签: sql-server dynamic-sql table-variable

我对动态SQL和SQL Server一般都很陌生,但我想迭代information_schema.tables中的表列表。每次迭代都有一个varchar变量,列出要在表名中搜索的月份年(where table_name like concat('USA_RETHHDs_%', @Month))。

然后将具有匹配日期的每个表放入varchar变量中。问题是,我想从table列表中获取information_schema.tables变量,但不确定如何做到这一点。因此,我正在尝试使用动态路由,将varchar变量嵌入到动态SQL查询中。但是,它期望table变量而不是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

1 个答案:

答案 0 :(得分:2)

尝试

set @sql = 'select * from ' + @Table
execute SP_EXECUTESQL @sql  

我还应该提一下,您可以在sp_executesql电话

中加入参数
DECLARE @Month VARCHAR(6)
DECLARE @Table VARCHAR(32)
DECLARE @sql NVARCHAR(MAX)
DECLARE @MonthCount INT
DECLARE @ParmDefinition NVARCHAR(500);


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 = N'select * from @param '
        SET     @ParmDefinition = N'@param varchar(500)'

        EXECUTE SP_EXECUTESQL @sql, @ParmDefinition, @param = @Table

        SELECT  @MonthCount = @MonthCount - 1
    END