简体   繁体   中英

How to omit certain values while generating XML from SQL (MS SQL Server)

We are generating XML out of our MS SQL Server, and we want to omit 0 values for one generated tag to be not generated in XML report.

Where condition doesn`t help, as then complete tag structure is ommited, not only one value.

SELECT                                     
    CONVERT(VARCHAR(255), [BONUS_AMOUNT]) AS [06_BONUS_AMOUNT]     ,
    CONVERT(VARCHAR(255), [MAXIMUM_AMOUNT]) AS [07_MAXIMUM_AMOUNT]
FROM #xmldatarider rid

How to generate XML tag for certain column, only when value is not equal to Zero, please?

so Lets`say, this row would be ommited:

<tns:attributeCurrency xmlns:tns="BigDataFeed" idx="4" col="4" name="BONUS_AMOUNT" value="0" currency="EUR" />

But it would be kept in case there is other value than 0.

Really simplified version: I have a table, out of which I create XML file: code: SELECT PolicyKey, PremiumDebtAmount, DebtKey FROM [DWH].[tgt].[Debt] where PolicyKey IN (4,5) for xml PATH('Debt'), elements go

Result is 2 XML parent tags, both with 3 values:

<Debt> <PolicyKey>4</PolicyKey> <PremiumDebtAmount>7.47</PremiumDebtAmount> <DebtKey>241547</DebtKey> </Debt> <Debt> <PolicyKey>5</PolicyKey> <PremiumDebtAmount>5.28</PremiumDebtAmount> <DebtKey>241548</DebtKey> </Debt>

I want not to show the tag PremiumDebtAmount, when it s 5.28.
I can
s 5.28.
I can
s 5.28.
I can
t use where condition, because all tags from parent are then ommited.

Code:

SELECT PolicyKey, PremiumDebtAmount, DebtKey 
FROM [DWH].[tgt].[Debt] 
where PolicyKey IN (4,5) and PremiumDebtAmount<>5.28 
for xml PATH('Debt'), elements

Result:

<Debt> 
    <PolicyKey>4</PolicyKey> 
    <PremiumDebtAmount>7.47</PremiumDebtAmount> 
    <DebtKey>241547</DebtKey> 
</Debt>

What I do need to see is:

<Debt> 
    <PolicyKey>4</PolicyKey> 
    <PremiumDebtAmount>7.47</PremiumDebtAmount> 
    <DebtKey>241547</DebtKey> 
</Debt> 
<Debt> 
    <PolicyKey>5</PolicyKey> 
    <DebtKey>241548</DebtKey> 
</Debt> 

And my question is how :)

Thank you

Here's a solution to a slightly simplified version of your problem, showing the use of nested typed XML:

DECLARE @Debt TABLE (
    PolicyKey NVARCHAR(100),
    PremiumDebtAmount DECIMAL(5, 2),
    DebtKey INT
)
INSERT @Debt VALUES (4, 7.47, 241547), (5, 5.28, 241548)

SELECT 
    PolicyKey, 
    (
        SELECT PremiumDebtAmount 
        WHERE PremiumDebtAmount <> 5.28
        FOR XML PATH(''), TYPE
    ),
    DebtKey
FROM @Debt
FOR XML PATH('Debt')

Result:

<Debt>
    <PolicyKey>4</PolicyKey>
    <PremiumDebtAmount>7.47</PremiumDebtAmount>
    <DebtKey>241547</DebtKey>
</Debt>
<Debt>
    <PolicyKey>5</PolicyKey>
    <DebtKey>241548</DebtKey>
</Debt>

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM