I have a table like this
Id Name FromAddress ToAddress
1 Joey ABC JKL
2 Joey DEF MNP
3 Joey GHI OQR
I believe the problem is the IN () expression in the PIVOTs. The column list explicitly has to be a list of fields names, not a function and not a list of varchar literals or function values. You've got a REPLACE() function in there. The engine expects to be looking for a field named [REPLACE] and then gets confused by the open parentheses that shows up.
This is valid (square brackets for emphasis):
SELECT VendorID, Employee, Orders
FROM
(SELECT VendorID, Emp1, Emp2, Emp3, Emp4, Emp5
FROM pvt) p
UNPIVOT
(Orders FOR Employee IN
([Emp1], [Emp2], [Emp3], [Emp4], [Emp5])
)AS unpvt;
This is not:
SELECT VendorID, Employee, Orders
FROM
(SELECT VendorID, Emp1, Emp2, Emp3, Emp4, Emp5
FROM pvt) p
UNPIVOT
(Orders FOR Employee IN
('Emp1', 'Emp2', 'Emp3', 'Emp4', 'Emp5')
)AS unpvt;
And this is not valid:
SELECT VendorID, Employee, Orders
FROM
(SELECT VendorID, Emp1, Emp2, Emp3, Emp4, Emp5
FROM pvt) p
UNPIVOT
(Orders FOR Employee IN
(REPLACE('Emp1','1','A'), REPLACE('Emp2','2','B'))
)AS unpvt;
Replace the execute(@query) with a select @query or print @query to see the query your code generated and troubleshoot the syntax in a query analyzer that way. Then work backwards.
You want to do the REPLACE() at the same level you're building the query. The query that ends up in the @query variable should already have the column names fixed.
Alternately, you could generate @colsFromLabels, @colsToLabels, @colsFrom and @colsTo with the former two have the 'from' and to bits added and the latter two just being column names.
Your desired output is a little gross as far as square bracket escaping, too.