日期:2014-05-19  浏览次数:20700 次

*******必须声明表变量 "@shu"。
declare   @result_list   table(   m   int,   n   int)
declare   @shu   table(   h   int,   i   int,   j   int,   k   int,   m   int)
insert   into   @result_list   select   TitleID,count(*)c   from   soft   group   by   TitleID

DECLARE   @s   VARCHAR(800)  
SET   @s= 'insert   into   @shu   select   '  
select   @s   =   @s   +   ',max(case   when   TitleID= '   +   Convert(varchar(10),tt)   +   '   then   c   end)[ '
+   Convert(varchar(10),tt)   +   '] '   from   (select   m   as   tt   from   @result_list)A  
SET   @s=stuff(@s+ '   from   @result_list ',25,1, ' ')
---select   @s
exec   (@s)
帮我检查下哪错了!!!


---------------
消息   1087,级别   15,状态   2,第   1   行
必须声明表变量   "@shu "。
消息   1087,级别   15,状态   2,第   1   行
必须声明表变量   "@result_list "。


------解决方案--------------------
表变量作用域的问题

table 变量的行为类似于局部变量,有明确定义的作用域。该作用域为声明该变量的函数、存储过程或批处理。
------解决方案--------------------
--试试
create table result_list( m int, n int)
create table shu( h int, i int, j int, k int, m int)
insert into result_list select TitleID,count(*)c from soft group by TitleID

DECLARE @s VARCHAR(800)
SET @s= 'insert into shu select '
select @s = @s + ',max(case when TitleID= ' + Convert(varchar(10),tt) + ' then c end)[ '
+ Convert(varchar(10),tt) + '] ' from (select m as tt from result_list)A
SET @s=stuff(@s+ ' from result_list ',25,1, ' ')
exec (@s)

drop table result_list,shu

------解决方案--------------------
DECLARE @s VARCHAR(800)
SET @s = 'declare @result_list table( m int, n int) '
SET @s = @s + 'declare @shu table( h int, i int, j int, k int, m int) '
SET @s = @s + 'insert into @result_list select TitleID,count(*)c from soft group by TitleID '
SET @s = @s + 'insert into @shu select '
SET @s = @s + ',max(case when TitleID= ' + Convert(varchar(10),tt) + ' then c end)[ '
+ Convert(varchar(10),tt) + '] ' from (select m as tt from @result_list)A
SET @s=stuff(@s+ ' from @result_list ',25,1, ' ')
---select @s
exec (@s)
------解决方案--------------------
你的錯誤原因是,表變量是在外部定義的,而你想用在EXEC內部。

可以改用臨時表來做。

但是你的語句還有些錯誤.

比如,soft的TitleID是不固定的,那麼你的新表的列數應該是不固定的,而你卻定義了一個固定結構的表,往裡面插入數據。

另外還有些別的錯誤。
------解决方案--------------------
Create Table TEST
(TitleID Int,
c Int)
Insert TEST Select 11, 3
Union All Select 12, 3
Union All Select 13, 2
Union All Select 14, 5
Union All Select 15, 1
GO
Declare @S Varchar(8000)
Select @S = ' '
Select @S = @S + ', SUM(Case TitleID When ' ' ' + Rtrim(TitleID) + ' ' ' Then c Else 0 End) As [ ' + Rtrim(TitleID) + '] '
From TEST Group By TitleID
Select @S = ' Select ' + Stuff(@S, 1, 1, ' ') + ' Into #T From TEST ; Select * From #T; Drop table #T '