使用EXEC创建SQL临时表

时间:2015-06-09 19:04:04

标签: sql-server

我需要动态创建临时表,因为我事先并不知道我将使用的所有列。

因此,我要说我需要创建一个包含固定列的表

Item int, start int, end int 

我设法将变量列(Rcpt1 int, Rcpt2 int)放入nvarchar变量@columnsRcpt +另外两个变量列@Start@End。 所以我尝试构建我的查询:

@qry = 'CREATE TABLE #InvRcpt (SKU nvarchar(25), '
        + @Start + ' int' 
        + @columnsRcpt +', 
          Vendu int, 
          [Retrait d''inventaire] int, 
          Ajout int, 
          Solde int, ' 
          + @End + ' int)'
Exec(@qry)
select * from #InvRcpt

但它不起作用,我确定我会错过一些语法,你能帮我解决这个问题吗? 谢谢

3 个答案:

答案 0 :(得分:6)

您可以做的一件事是,如果要通过在动态查询中修改临时表来访问动态查询之外的临时表,则将其声明为在动态查询之外。说

CREATE TABLE #InvRcpt (SKU nvarchar(25))
declare @qry nvarchar(500)
set @qry = 'alter TABLE #InvRcpt add '
    + @Start + ' int,' 
    + @columnsRcpt +', 
      Vendu int, 
      [Retrait d''inventaire] int, 
      Ajout int, 
      Solde int, ' 
      + @End + ' int'
Exec(@qry)
select * from #InvRcpt

然后你应该得到输出并在外面使用临时表。

答案 1 :(得分:2)

假设您的环境使用分号(;)作为命令终止符,请尝试以下

@qry = 'CREATE TABLE #InvRcpt (SKU nvarchar(25), '
        + @Start + ' int' + @columnsRcpt +', Vendu int, [Retrait d''inventaire] int
        , Ajout int, Solde int, ' + @End + ' int)'
        + ';' 
        + 'select * from #InvRcpt;'

Exec(@qry)

正如Sean Lange先前的评论所指出的那样,您需要使用CREATE在同一批次中调用SELECT语句才能获得结果。

答案 2 :(得分:0)

通过尝试以下方法在EXEC(@qry)之外创建#InvRcpt:

如果OBJECT_ID('tempdb .. ## InvRcpt1')为空 开始 EXEC('CREATE TABLE#InvRcpt1(SKU nvarchar(25),'+ @Start +'int'+ @columnsRcpt +',           Vendu int,           [Retrait d''inventaire] int,           Ajout int,           Solde int,'+ @End +'int)')

END

SELECT * INTO #InvRcpt 来自## InvRcpt1

SELECT * 来自#InvRcpt

相关问题