-2

我需要编写一个 Sql 服务器查询来生成这个 xml 文件。

<Ob name="MData">
  <FieldList>
    <Field name="ID">0980</Field>
    <Field name="IDDes">Working</Field>
    <Field name="Category">Arts Student</Field>
  </FieldList>
</Ob>

我的表如下所示:

CREATE TABLE [dbo].[MData](
  [ID] [nvarchar](50) NULL, 
  [IDDes] [nvarchar](50) NULL, 
  [Category] [nvarchar](50) NULL)

这是我到目前为止所做的,但我需要一些专家的帮助来获得确切的 XML 格式。

Select ( 
    Select 
        'ID' as '@name',
        ID 
    from 
        dbo.MData as B 
    Where A.ID = B.ID 
    FOR XML Path('Field'), Type 
), ( 
    Select 
        'IDDes' as '@name' , 
        IDDes 
        From dbo.MData As B 
    Where A.ID = B.ID 
    FOR XML Path('Field'), Type 
), ( 
    Select 
        'Category' as '@name' , 
        category 
    From dbo.MData As B 
    Where A.ID = B.ID 
    FOR XML Path('Field'), Type 
) 
FROM dbo.MData As A 
FOR XML path('FieldList'), Root('OB')
4

1 回答 1

1

这是你的选择...

Select ( 
    Select 
        'ID' as '@name',
        ID 
    from 
        dbo.MData as B 
    Where A.ID = B.ID 
    FOR XML Path('Field'), Type 
), ( 
    Select 
        'IDDes' as '@name' , 
        IDDes 
        From dbo.MData As B 
    Where A.ID = B.ID 
    FOR XML Path('Field'), Type 
), ( 
    Select 
        'Category' as '@name' , 
        category 
    From dbo.MData As B 
    Where A.ID = B.ID 
    FOR XML Path('Field'), Type 
) 
FROM dbo.MData As A 
FOR XML path('FieldList'), Root('OB')

用 . 包装您的每个值(SELECT your_value)

像这样:

Select ( 
    Select 
        'ID' as '@name',
        (SELECT ID)
    from 
        dbo.MData as B 
    Where A.ID = B.ID 
    FOR XML Path('Field'), Type 
), ( 
    Select 
        'IDDes' as '@name' , 
        (SELECT IDDes)
        From dbo.MData As B 
    Where A.ID = B.ID 
    FOR XML Path('Field'), Type 
), ( 
    Select 
        'Category' as '@name' , 
        (SELECT category)
    From dbo.MData As B 
    Where A.ID = B.ID 
    FOR XML Path('Field'), Type 
) 
FROM dbo.MData As A 
FOR XML path('FieldList'), Root('OB')
于 2013-07-14T19:01:55.917 回答