是否可以使用sqlxmlbulkload加载此xml?

时间:2018-06-15 16:08:43

标签: sql-server xml xsd sqlxml

是否可以使用sqlxmlbulkload将类似的xml加载到这些表中? XML:

<?xml version="1.0" encoding="utf-8"?>
<a>
    <b>
    <code>1</code>
    <ds1>1.11</ds1>
    <ds1>1.12</ds1>
    <ds1>1.13</ds1>
    <ds2>2.11</ds2>
    </b>

    <b>
    <code>2</code>  
    <ds1>1.21</ds1>
    <ds1>1.22</ds1>
    <ds2>2.21</ds2>
    <ds2>2.22</ds2>
    </b>

    <b>
    <code>3</code>      
    <ds1>1.31</ds1>
    <ds2>2.31</ds2>
    <ds2>2.32</ds2>
    </b>

    <b>
    <code>4</code>      
    <ds2>2.41</ds2>
    </b>
</a>

Sql server tables:

Create table b
    ([_id_b] int identity(1,1) NOT NULL
    ,[code] nvarchar(10) NULL
    ,Constraint PK_b primary key clustered ([_id_b])
    )
;
Create table ds
    ([_id_ds] int identity(1,1) NOT NULL
    ,[_id_b] int NOT NULL
    ,[ds] nvarchar(10) NULL
    ,[type] smallint not null constraint cs_type check ([type] between 1 and 2)
    ,Constraint PK_ds primary key clustered ([_id_ds])
    )

对于sqlxmlbulkload,此xml的xsd架构应该是什么? 这不是一个简单的问题! 注意,我需要将标记<ds1><ds2>加载到一个表ds中,这些是多个标记。 它有可能吗?

1 个答案:

答案 0 :(得分:0)

使用以下语句,您将从XML中提取值。将结果存储在表中应该非常简单:

DECLARE @xml XML=
'<a>
    <b>
    <code>1</code>
    <ds1>1.11</ds1>
    <ds1>1.12</ds1>
    <ds1>1.13</ds1>
    <ds2>2.11</ds2>
    </b>

    <b>
    <code>2</code>  
    <ds1>1.21</ds1>
    <ds1>1.22</ds1>
    <ds2>2.21</ds2>
    <ds2>2.22</ds2>
    </b>

    <b>
    <code>3</code>      
    <ds1>1.31</ds1>
    <ds2>2.31</ds2>
    <ds2>2.32</ds2>
    </b>

    <b>
    <code>4</code>      
    <ds2>2.41</ds2>
    </b>
</a>';

-查询

SELECT A.b.value('(code/text())[1]','nvarchar(10)') AS b_code
      ,B.ds.value('text()[1]','decimal(10,4)') AS ds_value
      ,B.ds.value('local-name(.)','nvarchar(100)') AS NodeName
FROM @xml.nodes('/a/b') AS A(b)
CROSS APPLY A.b.nodes('*[substring(local-name(),1,2)="ds"]') AS B(ds)

结果

b   ds      NodeName
1   1.1100  ds1
1   1.1200  ds1
1   1.1300  ds1
1   2.1100  ds2
2   1.2100  ds1
2   1.2200  ds1
2   2.2100  ds2
2   2.2200  ds2
3   1.3100  ds1
3   2.3100  ds2
3   2.3200  ds2
4   2.4100  ds2