1

我对动态 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
4

1 回答 1

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
于 2015-07-06T21:25:45.633 回答