用于创建动态表的脚本

时间:2014-12-03 10:24:51

标签: sql sql-server tsql stored-procedures temp-tables

我正在尝试创建一个动态脚本来创建多个表。以下是样本

--exec USP_Dynamic_tablescript
Create procedure USP_Dynamic_tablescript
as 
    DECLARE @SQLStmt nvarchar(3000)
    DECLARE @table_name nvarchar(3000)
    DECLARE @i int

    set @i=1

    while(@i<=3)
    begin
        set @table_name = '#tblSales' + convert(varchar(10),@i)

        SET @SQLStmt = 'create  TABLE ' + @table_name +  '( ' + ' CityId int , ' +
                       ' SalesPersonId int , ' + ' SalesAmount numeric(10,2), ' +
                       ' MetTarget nvarchar(2) ' + ' ) '+
                       ' ON [PRIMARY] WITH (DATA_COMPRESSION = NONE)'

        print @table_name

        EXEC sp_executesql @SQLStmt

        set @i = @i + 1
    end

    SELECT * from #tblSales1

    INSERT INTO #tblSales1(CityId, SalesPersonId, SalesAmount, MetTarget) 
    VALUES (1, 101, 1650.00, 'Y')

我需要在这些临时表上运行DML语句。

如果我尝试,我会收到以下错误。请帮助我理解范围,成功创建表但是如何在其上运行DML操作。

  

Msg 208,Level 16,State 0,Procedure USP_Dynamic_tablescript,Line 31
  无效的对象名称'#tblSales1'。

2 个答案:

答案 0 :(得分:0)

正如我在评论中提到的,您无法在动态查询中访问动态查询范围之外的临时表 已创建

替代方法是创建可在动态查询之外使用的Global TempTablePhysical table

DECLARE @SQLStmt nvarchar(3000)
DECLARE @table_name nvarchar(3000)
DECLARE @i int

set @i=1

while(@i<=3)
begin
    set @table_name = '##tblSales' + convert(varchar(10),@i)

    SET @SQLStmt = 'create  TABLE ' + @table_name +  '( ' + ' CityId int , ' +
                   ' SalesPersonId int , ' + ' SalesAmount numeric(10,2), ' +
                   ' MetTarget nvarchar(2) ' + ' ) '+
                   ' ON [PRIMARY] WITH (DATA_COMPRESSION = NONE)'

    print @table_name

    EXEC sp_executesql @SQLStmt

    set @i = @i + 1
end

SELECT * from ##tblSales1

答案 1 :(得分:0)

    CREATE PROCEDURE USP_Dynamic_tablescript
AS
DECLARE @SQLStmt NVARCHAR(3000)
    ,@table_name NVARCHAR(3000)
    ,@i INT

SET @i = 1

WHILE (@i <= 3)
BEGIN
    SET @table_name = '##tblSales' + convert(VARCHAR(10), @i)
    SET @SQLStmt = 'IF OBJECT_ID(''Tempdb..' + @table_name + ''') IS NOT NULL' + CHAR(10) + 
                    'DROP TABLE ' + @table_name + CHAR(10) + 
                    'CREATE  TABLE ' + @table_name + CHAR(10) + 
                    '(CityId int ,' + CHAR(10) + 
                    ' SalesPersonId int ,' + CHAR(10) + 
                    ' SalesAmount numeric(10,2),' + CHAR(10) + 
                    ' MetTarget nvarchar(2) )' + CHAR(10) + 
                    ' ON [PRIMARY] WITH (DATA_COMPRESSION = NONE)'

    PRINT @SQLStmt

    EXEC sp_executesql @SQLStmt

    SET @i = @i + 1
END

INSERT INTO ##tblSales1 (
    CityId
    ,SalesPersonId
    ,SalesAmount
    ,MetTarget
    )
VALUES (
    1
    ,101
    ,1650.00
    ,'Y'
    )

SELECT *
FROM ##tblSales1