I have the below query which returns what products are on what orderID.
SELECT P.Name,
STUFF (( SELECT ' | ' + CONVERT(VARCHAR(22) , SOD.SalesOrderID)
FROM Sales.SalesOrderDetail SOD
WHERE
P.ProductID = SOD.ProductID
FOR XML PATH ('')
), 1, 1, '')
as Orders
FROM Production.Product P
However, I am having trouble with the 'Nulls'. I've tried isnull is different parts of the code as well as a case statement but can't seem to figure where it would go.
If anyone can give me any help that would be great.
My guess is that the problematic NULL
s are in SOD.SalesOrderId
.
One way to handle them is by filtering them out:
SELECT P.Name,
STUFF (( SELECT ' | ' + CONVERT(VARCHAR(22) , SOD.SalesOrderID)
FROM Sales.SalesOrderDetail SOD
WHERE
P.ProductID = SOD.ProductID and SOD.SalesOrderId is not null
FOR XML PATH ('')
), 1, 1, '')
as Orders
FROM Production.Product P
Another way is to convert them to some acceptable representation:
SELECT P.Name,
STUFF (( SELECT ' | ' + coalesce(CONVERT(VARCHAR(22) , SOD.SalesOrderID), '<NULL>')
FROM Sales.SalesOrderDetail SOD
WHERE
P.ProductID = SOD.ProductID
FOR XML PATH ('')
), 1, 1, '')
as Orders
FROM Production.Product P
EDIT:
The NULL
s are being returned because there is no match in SalesOrderDetail
for the records. What would you want returned in this case?
To find those products:
select p.*
from Production.Product p left outer join
Sales.SalesOrderDetail sod
on p.ProductID = SOD.ProductID
where sod.ProductId is null;
If you want to filter them out, then use a subquery:
select t.*
from (<either of the above queries>) t
where t.Orders is not NULL
EDIT II:
If you want blanks to be returned, then wrap coalesce()
around the value:
SELECT P.Name,
coalesce(STUFF (( SELECT ' | ' + CONVERT(VARCHAR(22) , SOD.SalesOrderID)
FROM Sales.SalesOrderDetail SOD
WHERE
P.ProductID = SOD.ProductID
FOR XML PATH ('')
), 1, 1, ''), '')
as Orders
FROM Production.Product P
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.