我的猜测是有问题NULL
的 s 在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
另一种方法是将它们转换为一些可接受的表示:
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
编辑:
NULL
正在返回 s,因为记录中没有匹配项SalesOrderDetail
。在这种情况下,您希望返回什么?
要查找这些产品:
select p.*
from Production.Product p left outer join
Sales.SalesOrderDetail sod
on p.ProductID = SOD.ProductID
where sod.ProductId is null;
如果要过滤掉它们,请使用子查询:
select t.*
from (<either of the above queries>) t
where t.Orders is not NULL
编辑二:
如果要返回空白,请coalesce()
环绕该值:
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