Skip to content
Advertisement

Syntax Error when trying to use Dynamic Pivot Query

I’ve been playing around with the PIVOT function for a while. I have a table that looks like this

Every ClientID is repeated once for each month. Every month new rows are added to the table with a new period associated to the row. It’s an incrementing table.

What I need to do is to PIVOT the table, so that it basically ends up like this:

Naturally, I want my code to be dynamic. I don’t want to harcode every month like:

So I’ve been trying several dynamic solutions found in here, but none of them are working for me, and I don’t know why. And it’s driving me crazy.

This solutions gives me

Incorrect Syntax near ‘FOR’

My code below:

The second solution provided in the same link gives me

A variable that has been assigned in a SELECT statement cannot be included in a expression or assignment when used in conjunction with a from clause.

Which is kinda understandable, as the query tries to solve getting the DISTINCT values of [Period] in a recursive way, as far as I understood. However, everybody accepted that as a viable answer too.

My code below:

The third solution I tried gives me the same error noted above, with a similar syntax but not exactly the same. It tries to solve the DISTINCT [Period]s recursively.

My code below:

So, what exactly am I doing wrong?? Can anybody throw me a hint? I’m failing over solutions approved by the whole community, and I can’t understand why. I basically tried to understand the code, copied it, and replaced columns and tables. Just that. I didn’t change anything more. Thanks in advance!

Advertisement

Answer

Looking at your third solution.

First thing I notice is that you are not coalescing the initial null value of @ColumnName when you do your concatenation.

That should solve your problem.

If you would PRINT the result @ColumnName and @DynamicPivotQuery, before you execute it, it will usually show you where the problems are.

For versions of sql that do not support SELECT @Variable

SQL Azure and SQL DW only support using SET when setting variable values. You can use STRING_AGG() on these servers

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement