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?
 
PortletPaulfreelancerCommented:
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
 
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
 
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.