Select 查询 SQL XML 空元素

Select query with SQL XML empty element

我写了一个查询来从 table 中获取 XML 格式的数据,但是如果列没有任何数据那么它不会在 XML 输出中返回数据.请让我知道如何解决这个问题。

即使 table 列中没有带有空标记的数据,我也需要获取输出 - 就像这样 "</BatchEntryId>"。这里 BatchEntryId 在 table

中为 NULL

我的查询:

SELECT 
    Data.value('(/Data/Reference)[1]', 'nvarchar(10)') AS PolicyNumber,
    [RequestId],
    [BatchEntryId],
    [StatusCode],
    [PaymentMethodCode],
    Data.value('(/Data/Amount)[1]', 'nvarchar(10)') AS Amount
FROM 
    [dbo].[TransmissionData]
WHERE 
    RequestId = 2031070233
FOR XML RAW ('RequestRecord'), ELEMENTS, TYPE

我的输出:

<RequestRecord>
    <PolicyNumber>Policy034</PolicyNumber>
    <RequestId>2031070233</RequestId>
    <StatusCode>A</StatusCode>
    <PaymentMethodCode>1XCC</PaymentMethodCode>
    <Amount>200.00</Amount>
</RequestRecord>

问题是 'BatchEntryId',我没有在输出 XML 中得到它,因为该列具有 NULL 值。但我也需要在输出 XML 中将其作为空标记,例如 </BatchEntryId>.

请告诉我如何解决这个问题。

我正在寻找这样的输出:

<RequestRecord>
    <PolicyNumber>Policy034</PolicyNumber>
    <RequestId>2031070233</RequestId>
    <BatchEntryId/>
    <StatusCode>A</StatusCode>
    <PaymentMethodCode>1XCC</PaymentMethodCode>
    <Amount>200.00</Amount>
</RequestRecord>

你可以ISNULL它为一个空字符串

SELECT Data.value('(/Data/Reference)[1]', 'nvarchar(10)') as  PolicyNumber
       ,[RequestId]
       ,ISNULL([BatchEntryId], '') AS BatchEntryId
       ,[StatusCode]
       ,[PaymentMethodCode]
       ,Data.value('(/Data/Amount)[1]', 'nvarchar(10)') as  Amount
    FROM [dbo].[TransmissionData]
    WHERE RequestId = 2031070233
    FOR XML RAW ('RequestRecord'), ELEMENTS, TYPE

如果 BatchEntryId 不是 varcharnvarchar 你应该先施放它

ISNULL(CAST(BatchEntryId AS varchar(30)), '') AS BatchEntryId

请注意 SQL 服务器将其生成为

<BatchEntryId></BatchEntryId>

然而这在语义上等同于 XML 到

<BatchEntryId/>