2013-10-31 82 views
1

我想在PIVOT中動態地傳遞值。請檢查下面的代碼,我得到了錯誤 - 必須聲明標量變量「@empid」。請幫我...在SQL透視中添加動態值

declare @empid nvarchar(20), @fromdate date, @todate date, @cols nvarchar(max), @query nvarchar(max) 
set @empid = 'EC0100' 
set @fromdate = '10/01/13' 
set @todate = '10/31/13' 

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(c._Date) 
     FROM MIS_BM_Calendar c 
     where c._Date between @fromdate and @todate 
     FOR XML PATH(''), TYPE 
     ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'') 

set @query = 'select * from 
(
select e.UserName, c._Date ,SUM(DATEDIFF(SS,0,c.TimeTaken)) As TimeTaken from MIS_BM_Users e 
inner join MIS_Opus c on 
e.EmpId=c.EmpId 
where [email protected] and c._Date between @fromdate and @todate 
group by c._Date, e.UserName 
) As SourceTable 
Pivot 
(
SUM(TimeTaken) for _Date In ('+ @cols +') As Pvt' 

execute(@query) 

回答

1

我自己找到了。這裏是正確的代碼...

ALTER Procedure [dbo].[MIS_AccountReport] (@AccountManagerId nvarchar(20), @Startdate datetime, @Enddate datetime, @Condition1 nvarchar(20),@condition2 nvarchar(20) 
) 
As 
Begin 
declare @cols nvarchar(max), @query AS VARCHAR(MAX), @hr nvarchar(10), @min nvarchar(10) set @hr='Hr(s)' 
set @min='Min(s)' 

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(convert(nvarchar(20),c._Date, 101)) 
     FROM MIS_BM_Calendar c 
     where c._Date between @Startdate and @Enddate 
     FOR XML PATH(''), TYPE 
     ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'') 



set @query= 'select UserName, '[email protected]+' from 
(
select e.UserName, c._Date ,SUM(DATEDIFF(SS,0,c.TimeTaken)) As 
TimeTaken from MIS_BM_Users e 
inner join MIS_Opus c on e.EmpId=c.EmpId 
where (e.AccountManagerID='''[email protected]+''') 
and c.Category not in ('''[email protected]+''', '''[email protected]+''') 
group by c._Date, e.UserName 
) As SourceTable 
Pivot 
(
SUM(TimeTaken) for _Date in ('[email protected]+') 
) As Pvt' 

execute(@query) 
End