SELECT返回NULL而不是消除不适用的行

时间:2017-02-13 15:00:34

标签: sql sql-server xml tsql

以下查询为表中符合条件的每一行生成一行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

我想知道为什么我的查询会生成这些记录?

1 个答案:

答案 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值(如您所见)。