I am getting an error described in the title where my code looks like this:
declare
@cols numeric(10,0),
@sql numeric(10,0)
select @cols = isnull(@cols + \', \'
You've declared @cols as numeric(10,0), but you're trying to assign text to it.
Probably need to declare it as nvarchar(max).
P.s. by concatenating AmountPayd you're suppose to get a list of customers?
declare
--@cols numeric(10,0),
--@sql numeric(10,0)
@cols varchar(max),
@sql varchar(max)
--Here you are setting @cols to a concatenated list of the amounts in your table
--The problem is you are trying to concat a decimal or integer into a string without casting it
--This is the same as doing 'A' + 1 and wanting to get A1. You first have to cast it.
--Notice the CAST(T.AmountPayd AS VARCHAR). But cols still needs to be a varchar in your declaration.
select @cols = isnull(@cols + ', ', '') + '[' + CAST(T.AmountPayd AS VARCHAR) + ']' from (select distinct AmountPayd from t1) as T
--Here you are building your dynamic SQL, which is a string which is why @sql must be varchar or nvarchar
select @sql = '
select *
from t1 as T
pivot
(
sum(T.AmountPayd) for T.Customer in (' + @cols + ')
) as P'
exec sp_executesql @sql = @sql
You've almost copied this example line for line, you just missed the declaration of your variables.
http://sqlhints.com/2014/03/18/dynamic-pivot-in-sql-server/