0
我正在使用SQL Server 2008,并且正在尝试根据用户的选择创建临时表。使用动态SQL和光标在临时表中创建列
消息102,级别15,状态1,行1个
附近有语法错误 '01':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
当我虽然运行它,我得到这些错误。
消息208,级别16,状态0,行47
无效的对象名称'## aa'。
最终输出应基于@ trsfrom和@trsto日期范围之间有多少商店进行了交易。所以,如果3个店在这一期间的销售,我正在寻找的结果是(01,02和03是存储名称):
MainGroup | SubGroup | SubSubGroup | Season | Vendor | 01 | 02 | 03 | Total
----------------------------------------------------------------------------
| | | | | | | |
在RPTrs的STOREID场是一个varchar(5)如果是问题。但商店列将显示日期范围内的销售金额。
FYI,['QUOTENAME()'](http://msdn.microsoft.com/en-us/library/ms176114.aspx)是优选的(和更容易),因为它也可以处理标识符名称内的分隔符 – Pondlife 2013-02-14 21:50:31