2016-11-25 85 views
0

我正在学习编写动态查询,所以道歉如果下面是混乱。动态选择查询与枢轴

我的问题是为什么下面的行不起作用。 @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

你今天早些时候提出了一个关于这个查询的问题,这里的问题也非常多。你的代码评估为'... in('[x],[y]')',你想要的是... ...('[x]','[y]')'。 – HoneyBadger

回答

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