Sqlserver
 sql >> Base de Dados >  >> RDS >> Sqlserver

Outro pivô com campos dinâmicos

DECLARE @QUERY NVARCHAR(MAX)

DECLARE @Annos TABLE(Anno INT)

INSERT INTO @Annos
SELECT DISTINCT Anno FROM TEST

DECLARE @Annuals VARCHAR(MAX)
DECLARE @Annuals_New VARCHAR(MAX)

SELECT @Annuals = COALESCE([email protected]+'],[' ,'[') +CONVERT(VARCHAR(10),A.Anno)
FROM @Annos A

SET @Annuals_New = @Annuals+']' 
SELECT @QUERY='SELECT * FROM TEST PIVOT (MAX(DonaAnno) FOR Anno IN ('[email protected]_New+'))AS [pivot]'

EXEC SP_EXECUTESQL  @QUERY

Isso ajudaria.;-)