以下查询为表中符合条件的每一行生成一行Xml代码:
SELECT
(
SELECT
[memberid],
[purchaseid],
CONVERT(DATE, [time]) AS [time],
[depID],
[theme],
[parentgroup],
(SELECT
[transactionid],
[quantity],
[price],
[articlenumber],
[articlename],
[articlesubgroupname],
[brand],
[articlecategory],
[maincategory]
FOR XML PATH('transaction'), TYPE) AS transactions
WHERE
quantity > 0 AND
memberid IS NOT NULL AND
DATALENGTH(RTRIM(LTRIM(memberid))) > 0
FOR XML PATH('receipt')) AS rowXml
FROM
TransactionsDSEDelta AS t
当我运行查询时,我得到的是quantity > 0
,而不是消除条件NULL
不适用的行。这意味着如果表TransactionsDSEDelta
中有10条记录,其中只有5条记录为正quantity
,则返回所有10条记录,但其中5条记录为NULL
。
我想知道为什么我的查询会生成这些记录?
答案 0 :(得分:2)
where
应位于外部查询中:
SELECT (
SELECT
[memberid],
[purchaseid],
CONVERT(DATE,[time]) AS [time],
[depID],
[theme],
[parentgroup],
(
SELECT
[transactionid],
[quantity],
[price],
[articlenumber],
[articlename],
[articlesubgroupname],
[brand],
[articlecategory],
[maincategory]
FOR XML PATH('transaction'), TYPE
) AS transactions
FOR XML PATH('receipt')
) AS rowXml
FROM TransactionsDSEDelta AS t
WHERE quantity > 0 AND
memberid IS NOT NULL AND
DATALENGTH(RTRIM(LTRIM(memberid))) > 0;
您无法过滤SELECT
语句中的行。您需要过滤WHERE
中的行。您的原始查询基本上是:
select . . .,
(select . . .
FOR XML PATH('receipt')
)
from TransactionsDSEDelta AS t;
这会选择TransactionsDSEDelta
中的所有内容。如果在子查询中筛选出某些内容,则会获得NULL
值(如您所见)。