2012-12-21 29 views
0

我已經嘗試了幾個組合的包裝最後選擇使用PIVOT其結果圈地選擇使用PIVOT

這是代碼

DECLARE @cols VARCHAR(1000) 
DECLARE @sqlquery VARCHAR(2000) 

SELECT @cols = STUFF((SELECT distinct ',' + QuoteName(idIndice) 
         FROM tgpwebged.dbo.sistema_Indexacao as a FOR XML PATH('') 
         ), 1, 1, '')  

SET @sqlquery = 'WITH TempTable AS 
       ( 
        select distinct a.id, b.idIndice, b.valor 
        from tgpwebged.dbo.sistema_Documentos as a 
        join tgpwebged.dbo.sistema_Indexacao as b on a.id = b.idDocumento 
        join tgpwebged.dbo.sistema_DocType as c on a.idDocType = c.id 
        join tgpwebged.dbo.sistema_DocType_Index as d on c.id = d.docTypeId 
        where d.docTypeId = 40  
        and (b.idIndice = 11 AND b.valor = ''11111111'' OR b.idIndice = 12 AND b.valor = ''11111'') 
       ) 
       SELECT * FROM TempTable t1 
         WHERE ((select count(*)   
         from TempTable t2   
         where t1.id = t2.id AND t1.valor != t2.valor) = 1)base 
       PIVOT 
       (
        Max(valor) 
        FOR [idIndice] IN (' + @cols + ') 
       ) AS finalpivot' 

EXECUTE (@sqlquery) 

這當然不會這麼努力做我需要附上圓括號或somenthing這樣做才能完成?

+0

我只是需要一個好的就可以,或者你不能這樣做。谷歌沒有任何相關的。我傾向於認爲這是不可能的。我很想知道爲什麼我不再犯這個錯誤 – Augusta

+0

你爲'@ cols'獲得什麼價值?你還得到什麼錯誤信息?如果你可以讓'@ sqlquery'運行在'EXECUTE()'之外,那麼它應該在'EXECUTE()'中運行。 –

回答