联盟在xml中选择查询

时间:2014-06-27 06:34:28

标签: sql xml tsql

我从表中选择数据为xml。我使用xml路径,我成功了。但是在xml中我还需要添加一个名为return as dummy的部分,稍后再使用。我也有select查询将返回部分作为xml。但现在我需要将这些选择查询联合起来以获得单个xml。

我的代码

    SELECT 
 CAST(IDNO AS VARCHAR(8)) AS [IDNO]         
 ,CAST(Code AS VARCHAR(4)) AS [CODE]         
 ,CAST(Amt AS VARCHAR(18)) AS [Amt]         
 FROM tbl1
 FOR XML PATH('ITEM'), ROOT('Table1'), TYPE 


SELECT 
'' AS INAME
,'' AS UNQ_ID
,'' AS STATUS
FOR XML PATH('IT_RETURN')

请告诉我。

编辑:我的预期输出是

<Table1>
  <ITEM>
    <IDNO>0283883</IDNO>
    <CODE>ABC</CODE>
    <Amt>20</Amt>
  </ITEM>
  <ITEM>
    <IDNO>0374747</IDNO>
    <CODE>DHF</CODE>
    <Amt>10</Amt>
  </ITEM>
</Table1>
<IT_RETURN>
  <INAME></INAME>
  <UNQ_ID></UNQ_ID>
  <STATUS></STATUS>
</IT_RETURN>

2 个答案:

答案 0 :(得分:0)

使用以下查询:

    SELECT IDNO
,CODE
,Amt
FROM
(
    SELECT 
    CAST('56' AS VARCHAR(8)) AS [IDNO]         
    ,CAST('44' AS VARCHAR(4)) AS [CODE]         
    ,CAST('33434' AS VARCHAR(18)) AS [Amt]         
    FROM tbl1

    UNION ALL

    SELECT 
    '' --AS INAME
    ,'' --AS UNQ_ID
    ,'' --AS STATUS
) t
FOR XML PATH('ITEM'), ROOT('Table1'), TYPE 

答案 1 :(得分:0)

以下将为您解决问题:

DECLARE @tbl1 TABLE (
    IDNO VARCHAR(8),
    Code VARCHAR(4),
    Amt VARCHAR(18)
)
INSERT INTO
    @tbl1
VALUES
    ( '0283883', 'ABC', '20' ),
    ( '0374747', 'DHF', '10' )

SELECT (
    SELECT 
        CAST(IDNO AS VARCHAR(8)) AS [IDNO],
        CAST(Code AS VARCHAR(4)) AS [CODE],
        CAST(Amt AS VARCHAR(18)) AS [Amt]         
    FROM
        @tbl1
    FOR XML PATH('ITEM'), ROOT('Table1'), TYPE 
    ), (
    SELECT 
        '' AS INAME
        ,'' AS UNQ_ID
        ,'' AS STATUS
    FOR XML PATH('IT_RETURN'), TYPE
) FOR XML PATH('')