Unable to add condition in FOR XML part

大憨熊 提交于 2019-12-25 09:51:22

问题


I have generated a FOR XML with the help from this Link. In the solution there is a condition

SELECT   
                    'String' as [Cell/Data/@ss:Type],
                    [Col1] as [Cell/Data],
                    '',
                    'String' as [Cell/Data/@ss:Type],
                    [Col2] as [Cell/Data],
                    '',

I want to add a condition to this part which says

SELECT      
                CASE 
                    WHEN COL1 LIKE '%SUP%'
                    THEN
                    'String' as [Cell/ss:Data/@ss:Type]
                    ELSE 
                    'String' as [Cell/Data/@ss:Type]
                    END ,
                [Col1] as [Cell/Data],
                '',

But i am getting issues. Kindly help me with this.

This basic code above showing the Syntax error. If i add

SELECT      
                    CASE 
                        WHEN COL1 LIKE '%SUP%'
                        THEN
                        (SELECT 'String' as [Cell/ss:Data/@ss:Type])
                        ELSE 
                        (SELECT 'String' as [Cell/Data/@ss:Type])
                        END ,
                    [Col1] as [Cell/Data],
                    '','

Then the generated XML is not correct


回答1:


If I understand what you're saying, then if Col1 contains the string "SUP", you want this tag in your final XML:

<ss:Data ss:Type="String">SomethingContainingSup</ss:Data>

Otherwise, you want this expression:

<Data ss:Type="String">SomethingElse</Data>

I think you can get that with this SQL fragment:

SELECT CASE WHEN COL1 LIKE '%SUP%' THEN 'String' END  as [Cell/ss:Data/@ss:Type],
       CASE WHEN Col1 Like '%SUP%' THEN Col1 END as [Cell/ss:Data], 
       CASE WHEN COL1 NOT LIKE '%SUP%' THEN 'String' END  as [Cell/Data/@ss:Type],                    
       CASE WHEN Col1 NOT Like '%SUP%' THEN Col1  END as [Cell/Data],
       ''

Why yours didn't work: you can't make the name of a column (or of an XML element) conditional. The closest you can get is to make one or the other expression evaluate to null, in which case it won't be rendered in the final XML.



来源:https://stackoverflow.com/questions/40048091/unable-to-add-condition-in-for-xml-part

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!