2011-06-08 43 views
0

我的SP的身體如下...當我試圖運行它,然後我得到錯誤。我只是不明白爲什麼會拋出錯誤......實際的錯誤在哪裏。請幫幫我。無法捕捉存儲過程中的錯誤在SQL服務器

Create table #jobs (id int identity(1,1),Specialist varchar(50),JID int) 
insert into #jobs values('ANA', 1) 
insert into #jobs values('ANA', 5) 
insert into #jobs values('ANA', 9) 
insert into #jobs values('ANA', 7) 
insert into #jobs values('ANA', 6) 

insert into #jobs values('GEN', 2) 
insert into #jobs values('GEN', 3) 
insert into #jobs values('GEN', 11) 
insert into #jobs values('GEN', 13) 
insert into #jobs values('GEN', 45) 
insert into #jobs values('GEN', 23) 
insert into #jobs values('GEN', 28)  
insert into #jobs values('GEN', 41) 
insert into #jobs values('GEN', 49) 
insert into #jobs values('GEN', 52) 

insert into #jobs values('robin', 12) 
insert into #jobs values('robin', 15) 
insert into #jobs values('robin', 17) 

declare @i smallint, @j smallint = 0 
; with cte as (select COUNT(*) cnt FROM #jobs group by Specialist) select @i=MAX(cnt) from cte 

declare @sql nvarchar(max) 
set @sql = N' 
;with cte as (
     select distinct Specialist from #jobs 
) 
select 
     Specialist ' 

while @i > @j 
begin 
     set @j = @j + 1; 
     set @sql = @sql + N' 
     ,(
       select id from (
         select 
           rn = row_number() over (partition by Specialist order by id), 
           id 
         from #jobs 
         where Specialist = cte.Specialist 
       ) t 
       where rn = ' + cast(@j as varchar(3)) + ' 
     ) as id 
     ' 
end 

set @sql = @sql + N' from cte ' 
print @sql 
exec sp_executesql @sql 
+0

什麼錯誤訊息你接收? – 2011-06-08 10:03:37

+1

錯誤是什麼? – CristiC 2011-06-08 10:03:57

+0

該代碼在SQL 2008上運行良好(儘管這是一種執行數據透視操作的奇怪方式,因爲TSQL具有'PIVOT'運算符) – 2011-06-08 10:33:53

回答

2

你不能默認值分配給本地變量...所以才刪除 「= 0」 從這一行:

declare @i smallint, @j smallint = 0 ; with ct.... 

,所以它讀取...

declare @i smallint, @j smallint; with ct.... 

HTH。 戴夫

PS ...不要忘記,當你完成它放棄你臨時表...

+0

聲明變量時分配值的語法快捷方式在SQL 2008中是有效的T-SQL然後 – 2011-06-08 10:07:21

1

變化

declare @i smallint, @j smallint = 0 

DECLARE @i SMALLINT, @j SMALLINT 
SET @j = 0