SQL SERVER FOR XML EXPLICIT

时间:2013-06-03 19:03:55

标签: sql-server xml for-xml-explicit

我想将SELECT FOR XML EXPLICIT语句的结果分配给XML变量,例如

CREATE PROCEDURE BILLING_RESPONSE 
AS   DECLARE @Data AS  XML

SET @Data = (SELECT

                1 AS Tag,
                NULL AS Parent,
                NULL AS 'CallTransactions!1!',
                NULL AS 'TCALTRS!2!TRS_DAT_TE!cdata',
                NULL AS 'TCALTRS!2!TRS_CRT_DT!Element'
            UNION ALL
            SELECT
                2 AS Tag,
                1 AS Parent, 
                NULL, 
                TRS_DAT_TE,
                TRS_CRT_DT  
             FROM TCALTRS 
             WHERE TRS_CRT_DT between CONVERT(date,GETDATE()-1) and CONVERT(date,getdate()) and 
             TRS_DAT_TE like '%(Submit Response)%'  
             FOR XML EXPLICIT           
            )

SELECT @DATA
GO

当我执行此查询时,我收到以下错误 消息1086,级别15,状态1,程序BILLING_RESPONSE,第22行 当FOR XML子句包含set运算符时,它们在视图,内联函数,派生表和子查询中无效。要解决此问题,请使用派生表语法包装包含set运算符的SELECT,并在其上应用FOR XML。

2 个答案:

答案 0 :(得分:0)

如果是这样,您就不需要@Data变量。让你的sp直接返回查询结果,你就完成了。

CREATE PROCEDURE BILLING_RESPONSE AS
SELECT

        1 AS Tag,
        NULL AS Parent,
        NULL AS 'CallTransactions!1!',
        NULL AS 'TCALTRS!2!TRS_DAT_TE!cdata',
        NULL AS 'TCALTRS!2!TRS_CRT_DT!Element'
    UNION ALL
    SELECT
        2 AS Tag,
        1 AS Parent, 
        NULL, 
        TRS_DAT_TE,
        TRS_CRT_DT  
     FROM TCALTRS 
     WHERE TRS_CRT_DT between CONVERT(date,GETDATE()-1) and CONVERT(date,getdate()) and 
     TRS_DAT_TE like '%(Submit Response)%'  
     FOR XML EXPLICIT

答案 1 :(得分:0)

错误并不是特别清楚,但它所说的是你不能在内联子查询中使用FOR XML子句,因为它包含一个UNION(一种集合运算符)

建议的解决方法是将子查询包装在其他内容中并单独调用它,例如:

CREATE PROCEDURE BILLING_RESPONSE 
AS   DECLARE @Data AS  XML

;WITH DATA AS(
               SELECT
                1 AS Tag,
                NULL AS Parent,
                NULL AS 'CallTransactions!1!',
                NULL AS 'TCALTRS!2!TRS_DAT_TE!cdata',
                NULL AS 'TCALTRS!2!TRS_CRT_DT!Element'
            UNION ALL
            SELECT
                2 AS Tag,
                1 AS Parent, 
                NULL, 
                TRS_DAT_TE,
                TRS_CRT_DT  
             FROM TCALTRS 
             WHERE TRS_CRT_DT between CONVERT(date,GETDATE()-1) and CONVERT(date,getdate()) and 
             TRS_DAT_TE like '%(Submit Response)%'  
             FOR XML EXPLICIT           
            )
SELECT @Data = (SELECT * FROM DATA FOR XML EXPLICIT)
SELECT @DATA
GO