我正在学习编写动态查询,如果下面的内容很混乱,请致歉。
我的问题是为什么下面这行不起作用。 @fxPair
变量以红色下划线标出。在我看来它是一个字符串变量,所以我无法看到问题?有没有更好的方法呢?
source pivot(max(Mvalue) for Currency in (@fxPair) as pvt
我的查询:
declare @FundsT table (fund nvarchar(10))
insert into @FundsT
select SubPot
from tblF
where Fund = @FundCode
order by SubPot
declare @fxPair nvarchar(max) = ''
select @fxPair = @fxPair + '[' + Currency + '], '
from tblCurrency
where DateH = @DateHld
and FundCode in (select fund from @FundsT)
group by Currency
set @fxPair = SUBSTRING(@fxPair, 1, len(@fxPair) - 1)
--print @fxPair
select *
from
(select
FundCode, IssueGrpType, Currency, Sum(MktValDirty) Mvalue
from
Holdings_SS
where
DateHolding = @DateHld
and FundCode in (select fund from @FundsT)
group by
FundCode, IssueGrpType, Currency) source
pivot
(max(Mvalue) for Currency in (@fxPair) as pvt
order by
FundCode, IssueGrpType
答案 0 :(得分:1)
您无法为透视列传递字符串。您可以检查它只是在普通查询中写入字符串而不使用任何变量。 本文描述了正确的方法。 Dynamic pivot
整个查询必须是字符串。在你的情况下,你应该尝试这样的事情
DECLARE @dpq AS NVARCHAR(MAX)
SET @dpq = 'select *
from
(select
FundCode, IssueGrpType, Currency, Sum(MktValDirty) Mvalue
from
Holdings_SS
where
DateHolding = @DateHld
and FundCode in (select fund from @FundsT)
group by
FundCode, IssueGrpType, Currency) source
pivot
(max(Mvalue) for Currency in (' + @fxPair + ') as pvt
order by
FundCode, IssueGrpType'
EXEC sp_executesql @dpq