我尝试了几种组合来包装最后一个选择以使用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 :(得分:0)
Try replace EXECUTE ( @sqlquery ) on EXEC @sqlquery