Eliminate row in XML based on criteria

ぃ、小莉子 提交于 2019-12-02 01:11:13

Instead of repeating the logic in many places I'd suggest to use a CTE (something like an ad-hoc VIEW) to pre-fetch your data. The rest is rather simple nesting with correlated sub-queries and much better to read:

Hope I got your logic correctly...

WITH cte AS
(       
        SELECT ls1.ID,ls1.PID,ls1.Code
              ,r1.ColumnNameXML,r1.GroupName,r1.GroupOrder
              ,CASE name
                WHEN 'Col1' THEN ISNULL(Col1,0)
                WHEN 'Col2' THEN ISNULL(Col2,0)
                WHEN 'Col3' THEN ISNULL(Col3,0)
                WHEN 'Col4' THEN ISNULL(Col4,0)
                WHEN 'Col5' THEN ISNULL(Col5,0)
                END AS ColumnValue
        FROM sys.columns
        CROSS JOIN TestXML ls1
        INNER JOIN XML_Columns_Reference r1
        ON sys.columns.name=r1.columnname   
        WHERE object_id = OBJECT_ID('TestXML') and r1.TableNameXML='T'
        and ls1.PID=@PID  
        and r1.ColumnName NOT IN (  SELECT [ColumnName] 
                                    FROM XML_NoUseCols_Ref  
                                    WHERE TableNameXML='T' and [Code]=ls1.Code
                                    GROUP BY ColumnName)
) 
SELECT GroupName AS [@n]
      ,(
        SELECT Code AS [@n]
              ,(
                SELECT cte3.ColumnNameXML AS [@n]
                      ,cte3.ColumnValue AS [col_value]
                FROM cte cte3
                WHERE cte3.GroupName=cte1.GroupName AND cte3.Code=cte2.Code
                ORDER BY cte3.ColumnNameXML
                FOR XML PATH('col'),TYPE
               )
        FROM cte cte2
        WHERE cte1.GroupName=cte2.GroupName
        GROUP BY cte2.Code
        ORDER BY cte2.Code
        FOR XML PATH('cat'),TYPE
       )
FROM cte cte1
GROUP BY GroupName,GroupOrder
ORDER BY GroupOrder
FOR XML PATH('grp');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!