读书人

*必须声明表变量 quot;@shuquot;解决方案

发布时间: 2012-02-04 15:43:08 作者: rapoo

*******必须声明表变量 "@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
(TitleIDInt,
cInt)
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 '


EXEC(@S)
GO
Drop Table TEST
--Result
/*
1112131415
33251
*/

读书人网 >SQL Server

热点推荐