使用动态SQL和Cursor在临时表中创建列

时间:2013-02-14 21:25:12

标签: sql-server-2008 cursor dynamic-sql

我正在使用SQL Server 2008,我正在尝试根据用户的选择创建临时表。

declare @x nvarchar(max), @mgchk int, @sgchk int, @ssgchk int, @seasonchk int, @vendorchk int, @storeid varchar(10), @trsfrom date, @trsto date

set @trsfrom = '1/1/12'
set @trsto = '1/1/13'
set @mgchk = 1
set @sgchk = 1
set @ssgchk = 1
set @seasonchk = 1
set @vendorchk = 1

set @x = 'create table ##aa ('

if @mgchk = 1
    set @x = @x + 'MainGroup varchar(20),'
if @sgchk = 1
    set @x = @x + 'SubGroup varchar(20),'
if @ssgchk = 1
    set @x = @x + 'SubSubGroup varchar(20),'
if @seasonchk = 1
    set @x = @x + 'Season varchar(20),'
if @vendorchk = 1
    set @x = @x + 'VendorID varchar(20),'

declare storecr Cursor scroll for
select distinct storeid from RPTrs where TRSDate between @trsfrom and @trsto
open storecr 
fetch next from storecr 
into @storeid 
while @@FETCH_STATUS = 0 begin
set @x = @x + @storeid + ' decimal(15,2),'
fetch next from storecr 
into @storeid 
end 
close storecr 
deallocate storecr

set @x = @x + 'Total decimal(15,2))'

execute sp_executesql @x

select * from ##aa

我在运行时遇到这些错误:

  

Msg 102,Level 15,State 1,Line 1
  '01'附近的语法不正确。
  Msg 208,Level 16,State 0,Line 47
  无效的对象名称'## aa'。

最终输出应基于在@trsfrom和@trsto日期范围之间进行交易的商店数量。因此,如果3家商店在此期间进行销售,我要找的结果是(01,02和03是商店名称):

MainGroup | SubGroup | SubSubGroup | Season | Vendor | 01 | 02 | 03 | Total
----------------------------------------------------------------------------
          |          |             |        |        |    |    |    |

RPTrs中的StoreID字段是varchar(5),如果这是问题。但商店列将显示日期范围之间的销售额。

1 个答案:

答案 0 :(得分:0)

找出问题所在。我在光标内的设置缺少[]

set @x = @x + '[' + @storeid +']' + ' decimal(15,2),'