0

我想将 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 子句在它们中无效。要解决此问题,请使用派生表语法包装包含集合运算符的 SELECT,并在其上应用 FOR XML。

4

2 回答 2

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
于 2013-06-03T19:10:45.953 回答
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
于 2015-06-11T16:35:28.500 回答