2016-11-25 116 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