SQL Server T-SQL使用FOR XML PATH将数据转换为XML

时间:2011-01-07 11:56:17

标签: sql sql-server xml tsql

我有以下表结构

ZoneID int
ZoneName varchar(50)

我需要将其转换为XML结构,如下所示,以导入另一个系统

    <Batch>
        <Record>
            <Insert>
                <Field>
                    <FieldName>ZoneID</FieldName>
                    <FieldValue>1</FieldValue>
                </Field>
                <Field>
                    <FieldName>ZoneName</FieldName>
                    <FieldValue>Interior</FieldValue>
                </Field>
            </Insert>
        </Record>
        <Record>
            <Insert>
                <Field>
                    <FieldName>ZoneID</FieldName>
                    <FieldValue>2</FieldValue>
                </Field>
                <Field>
                    <FieldName>ZoneName</FieldName>
                    <FieldValue>Exterior</FieldValue>
                </Field>
            </Insert>
        </Record>           
    </Batch>

到目前为止,我有这个:

SELECT 
(            
    (SELECT     
    'ZoneID' as 'FieldName',
    [ZoneID] as 'FieldValue'
    FROM [dbo].[Condition_t_Zones]
    WHERE ZoneID = [Condition_t_Zones].ZoneID
    FOR XML PATH('field'), TYPE)

) as 'Insert'

FROM [Condition_t_Zones]

FOR XML PATH('record'), ROOT('batch')

但我无法弄清楚如何使用另一个子查询选择其他字段'ZoneName'。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

管理让它工作,从我以前的测试中想到我在错误的地方有逗号和圆括号。

我的解决方案如下:

SELECT 
(
    (SELECT     
    'ZoneID' as 'FieldName',
    ZoneID as 'FieldValue'
    FROM [dbo].[Condition_t_Zones]
    WHERE ZoneID = [Condition_t_Zones].ZoneID
    FOR XML PATH('field'), TYPE) 
) as 'insert',
(            
    (SELECT     
    'ZoneName' as 'FieldName',
    ZoneName as 'FieldValue'
    FROM [dbo].[Condition_t_Zones]
    WHERE ZoneID = [Condition_t_Zones].ZoneID
    FOR XML PATH('field'), TYPE)        
) 
as 'insert'     
FROM [Condition_t_Zones]

FOR XML PATH('record'), ROOT('batch')

答案 1 :(得分:1)

这是一个肮脏的黑客,但它会起作用:

DECLARE @t TABLE
    (
      ZoneID INT
    , ZoneName VARCHAR(50)
    )
INSERT  INTO @t
        ( ZoneID, ZoneName )
VALUES  ( 1, 'Interior' ),
        ( 2, 'Exterior' )

SELECT  CONVERT(XML,  REPLACE(( SELECT 'ZoneID' AS 'Field/FieldName'
                                      , [ZoneID] AS 'Field/FieldValue'
                                      , 'ZoneName' AS 'Field2/FieldName'
                                      , [ZoneName] AS 'Field2/FieldValue'
                                 FROM   @t t2
                                 WHERE  ZoneID = t.ZoneID
                               FOR
                                 XML PATH('')
                               ), 'Field2', 'Field') ) AS 'Insert'
FROM    @t t
FOR     XML PATH('record')
          , ROOT('batch')