我想在PIVOT中动态传递值。请查看以下代码,我收到错误 - 必须声明标量变量“@empid”。请帮帮我......
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 e.TeamLeaderID=@empid 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)
答案 0 :(得分: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, '+@cols+' 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='''+@AccountManagerId+''')
and c.Category not in ('''+@Condition1+''', '''+@condition2+''')
group by c._Date, e.UserName
) As SourceTable
Pivot
(
SUM(TimeTaken) for _Date in ('+@cols+')
) As Pvt'
execute(@query)
End