Dynamic Pivot Null Value

I'm simply trying to put a null value in for the quantity amount. I was reading that the ISNULL goes into the Column values but I keep getting this error of:
'Msg 103, Level 15, State 4, Line 1
The identifier that starts with '[5302],0) as [[5302] FROM
(
SELECT DISTINCT pb.Color, o.OrderID, pb.Gender, pb.Size, pb.SizeNo, pb.PreBuyQty, od.Quantity
   ' is too long. Maximum length is 128.
Msg 105, Level 15, State 1, Line 1
Unclosed quotation mark after the character string '[5302],0) as [[5302] FROM
(
SELECT DISTINCT pb.Color, o.OrderID, pb.Gender, pb.Size, pb.SizeNo, pb.PreBuyQty, od.Quantity
    '.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '[5302],0) as [[5302] FROM
(
SELECT DISTINCT pb.Color, o.OrderID, pb.Gender, pb.Size, pb.SizeNo, pb.PreBuyQty, od.Quantity

Here is my syntax.
DECLARE @cols AS NVARCHAR(MAX),
		@query AS NVARCHAR(MAX)
SELECT @cols = STUFF((SELECT DISTINCT ',ISNULL([' + QUOTENAME(o.OrderID)+'],0) as ['+QUOTENAME(o.OrderID)+']'
        FROM         Orders AS o INNER JOIN
                      OrderDetails AS od ON o.OrderID = od.OrderID
                      RIGHT OUTER JOIN ProductsPreBuy AS pb ON od.ProductCode = pb.productcode
         WHERE (pb.Color = 'Royal Blue') AND (pb.Gender = 'Men')
         GROUP BY pb.Color, pb.Gender, pb.Size, pb.SizeNo, pb.PreBuyQty, od.Quantity, o.OrderID
         FOR XML PATH(''), TYPE
         ).value('.', 'NVARCHAR(MAX)')
         ,1,1,'')

Set @query = 'SELECT DISTINCT Color, Gender, Size, SizeNo, PreBuyQty,' + @cols + ' FROM
(
SELECT DISTINCT pb.Color, o.OrderID, pb.Gender, pb.Size, pb.SizeNo, pb.PreBuyQty, od.Quantity
        FROM Orders AS o
        INNER JOIN OrderDetails AS od 
            ON o.OrderID = od.OrderID 
        RIGHT OUTER JOIN ProductsPreBuy AS pb 
            ON od.ProductCode = pb.productcode
WHERE (pb.Color = ''Royal Blue'') AND (pb.Gender = ''Men'')
GROUP BY pb.Color, pb.Gender, pb.Size, pb.SizeNo, pb.PreBuyQty, od.Quantity, o.OrderID
) x 
PIVOT
(
    Sum(Quantity)
    for OrderID in (' + @cols + ')
    ) p 
ORDER BY SizeNo ' 

EXEC sp_executesql @query

Open in new window

Southern_GentlemanAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Anthony PerkinsCommented:
When using Dynamic SQL, you need to get in the habit of doing this:

PRINT @query
EXEC sp_executesql @query

If it is not obvious after doing this, then post the result here.
0
Anthony PerkinsCommented:
Also DISTINCT and GROUP BY are for the most part redundant and in your specific case totally unecessary.  Use one or the other and not both.
0
Southern_GentlemanAuthor Commented:
Made the updates and came up with the same error. Here is the removed Group By:

DECLARE @cols AS NVARCHAR(MAX),
		@query AS NVARCHAR(MAX)
SELECT @cols = STUFF((SELECT DISTINCT ',ISNULL([' + QUOTENAME(o.OrderID)+'],0) as ['+QUOTENAME(o.OrderID)+']'
        FROM         Orders AS o INNER JOIN
                      OrderDetails AS od ON o.OrderID = od.OrderID
                      RIGHT OUTER JOIN ProductsPreBuy AS pb ON od.ProductCode = pb.productcode
         WHERE (pb.Color = 'Royal Blue') AND (pb.Gender = 'Men')        
         FOR XML PATH(''), TYPE
         ).value('.', 'NVARCHAR(MAX)')
         ,1,1,'')

Set @query = 'SELECT DISTINCT Color, Gender, Size, SizeNo, PreBuyQty,' + @cols + ' FROM
(
SELECT DISTINCT pb.Color, o.OrderID, pb.Gender, pb.Size, pb.SizeNo, pb.PreBuyQty, od.Quantity
        FROM Orders AS o
        INNER JOIN OrderDetails AS od 
            ON o.OrderID = od.OrderID 
        RIGHT OUTER JOIN ProductsPreBuy AS pb 
            ON od.ProductCode = pb.productcode
WHERE (pb.Color = ''Royal Blue'') AND (pb.Gender = ''Men'')
) x 
PIVOT
(
    Sum(Quantity)
    for OrderID in (' + @cols + ')
    ) p 
ORDER BY SizeNo ' 
PRINT @query
EXEC sp_executesql @query

Open in new window

0
PortletPaulEE Topic AdvisorCommented:
Instead of trying to execute the generated SQL: just display it

& do this for each variable

e.g.

declare @cols as varchar(max)
set @cols = ....

set @query = ...

select @cols as gensql
union all
select @query
---------------------------------------------------------------
now look at the generated sql
---------------------------------------------------------------

You should  now see that you need 3 (not 2) variables, like this:

1. for the ISNULL( [field-here] , 0)  data used at line 12 above
2. for the use at line 25 which does NOT have the ISNULL()  stuff in it
3. the overall @query

eventually you should be able to see the entire @query content

paste just the @query string into this url: http://www.sql-format.com/

is it now valid sql?

if you still cannot identify the syntax error paste the content of @query into your next comment here.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Anthony PerkinsCommented:
As Paul has mentioned the whole point of the exercise was for you to post the result of the PRINT statement.  If that is not obvious to you, then comment out the line EXEC sp_executesql @query and post the result here.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.