我需要动态地创建一个临时表,因为我不知道我将要使用的所有列。
所以假设我需要创建一个固定列的表
Item int, start int, end int 和
变量列(Rcpt1 int, Rcpt2 int),我设法将它放入一个nvarchar变量@columnsRcpt +2多个变量列@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但是它不起作用,我确信我错过了一些语法方面的东西。
发布于 2015-06-09 19:20:34
如果要通过在动态查询中修改动态查询来访问动态查询外部的临时表,可以做的一件事是在动态查询之外声明它。说
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然后,您应该获得输出,并在外部使用temp表。
发布于 2015-06-09 19:20:55
假设您的环境使用分号(;)作为命令终止符,请尝试以下操作
@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先前的评论所指出的,您需要在同一个批中调用SELECT语句和CREATE,以便能够获得结果。
发布于 2018-01-23 11:06:54
在EXEC (@qry)之外创建#InvRcpt,方法如下:
IF OBJECT_ID('tempdb..##InvRcpt1') IS NULL
BEGIN
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
FROM ##InvRcpt1
SELECT *
FROM #InvRcpthttps://stackoverflow.com/questions/30740653
复制相似问题