I managed to apply the PIVOT statement you suggested to transpose the values of the records of a table as columns automatically:
DECLARE @PivotColumnas VARCHAR(MAX)
SELECT @PivotColumnas = COALESCE (@PivotColumnas + ',[' + IB_PDSBATCHATTRIBIDBI + ']', '[' + IB_PDSBATCHATTRIBIDBI + ']') FROM PDSBATCHATTRIB
DECLARE @PivotTablaSQL NVARCHAR(MAX)
SET @PivotTablaSQL = N' SELECT *
FROM (SELECT INVENTBATCHID, ITEMID, PDSBATCHATTRIB.IB_PDSBATCHATTRIBIDBI, PDSBATCHATTRIBVALUE FROM PDSBATCHATTRIBUTES
LEFT JOIN PDSBATCHATTRIB ON PDSBATCHATTRIBUTES.IB_PDSBATCHATTRIBIDBI = PDSBATCHATTRIB.IB_PDSBATCHATTRIBIDBI) AS TablaOrigen
PIVOT
(MIN(PDSBATCHATTRIBVALUE)
FOR IB_PDSBATCHATTRIBIDBI IN ('+ @PivotColumnas + ')) AS PivotTable'
EXECUTE (@PivotTablaSQL)
What I need is how to save the result as a query or create a table from this query. If I try to save the result as a query, I get the following error:
Incorrect syntax near the keyword ‘DECLARE’.
Thanks!
I found the solution, is very simple in fact!
I only have to add the command
INTO NewTablein theSELECTsentence oof the pivot table, just like that:This create a new table in the SQL database with the pivot table results.
Thanks all!