2

您好我是使用 XML 文件的新手,
我尝试将文件 ICD.xml 插入到 sql 表
XML 文件格式中,例如这样

   <letter>
<title>#</title>
<mainTerm>
  <title>1-propanol</title>
  <cell col="2">T51.3X1</cell>
  <cell col="3">T51.3X2</cell>
  <cell col="4">T51.3X3</cell>
  <cell col="5">T51.3X4</cell>
  <cell col="6">--</cell>
  <cell col="7">--</cell>
</mainTerm>
<mainTerm>
  <title>2-propanol</title>
  <cell col="2">T51.2X1</cell>
  <cell col="3">T51.2X2</cell>
  <cell col="4">T51.2X3</cell>
  <cell col="5">T51.2X4</cell>
  <cell col="6">--</cell>
  <cell col="7">--</cell>
</mainTerm>

我用这个代码

Declare @xml XML

Select  @xml  = CONVERT(XML,bulkcolumn,2) FROM OPENROWSET(BULK 'File Path',SINGLE_BLOB) AS X

SET ARITHABORT ON 
Insert into dbo.TestXML
    (
        C1,C3,C4,C5,C6,C7
    )


Select 
    p.value('C1[1]','VARCHAR(100)') AS C1,
    P.value('C2[1]','VARCHAR(100)') AS C2,
    P.value('C3[1]','VARCHAR(100)') AS C3,
    P.value('C4[1]','VARCHAR(100)') AS C4,
    P.value('C5[1]','VARCHAR(100)') AS C5,
    P.value('C6[1]','VARCHAR(100)') AS C6,
    P.value('C7[1]','VARCHAR(100)') AS C7,

From @xml.nodes('/letter/title') PropertyFeed(P)

但我的语法有错误你能帮我吗,如果有另一种方法thnx

4

1 回答 1

1
  1. 添加结束元素“字母”
  2. 在 INSERT 语句中添加 C2 列
  3. 去掉列列表中最后一列后面的逗号
  4. 将方法中的 XQuery 修改为节点('/letter/mainTerm')
  5. 在 .value 方法中为每个值添加条件

--

IF OBJECT_ID('dbo.TestXML') IS NOT NULL DROP TABLE dbo.TestXML
CREATE TABLE dbo.TestXML
 (
  C1 varchar(10),
  C2 varchar(10),
  C3 varchar(10),
  C4 varchar(10),
  C5 varchar(10),
  C6 varchar(10),
  C7 varchar(10)
  )

DECLARE @xml xml = 
  '<letter>
    <title>#</title>
    <mainTerm>
      <title>1-propanol</title>
      <cell col="2">T51.3X1</cell>
      <cell col="3">T51.3X2</cell>
      <cell col="4">T51.3X3</cell>
      <cell col="5">T51.3X4</cell>
      <cell col="6">--</cell>
      <cell col="7">--</cell>
    </mainTerm>
    <mainTerm>
      <title>2-propanol</title>
      <cell col="2">T51.2X1</cell>
      <cell col="3">T51.2X2</cell>
      <cell col="4">T51.2X3</cell>
      <cell col="5">T51.2X4</cell>
      <cell col="6">--</cell>
      <cell col="7">--</cell>
    </mainTerm>
   </letter>'

INSERT dbo.TestXML(C1, C2, C3, C4, C5, C6, C7)
SELECT p.value('(title)[1]', 'VARCHAR(100)') AS C1,
       p.value('(cell)[@col=2][1]','VARCHAR(100)') AS C2,
       p.value('(cell)[@col=3][1]','VARCHAR(100)') AS C3,
       p.value('(cell)[@col=4][1]','VARCHAR(100)') AS C4,
       p.value('(cell)[@col=5][1]','VARCHAR(100)') AS C5,
       p.value('(cell)[@col=6][1]','VARCHAR(100)') AS C6,
       p.value('(cell)[@col=7][1]','VARCHAR(100)') AS C7
FROM @xml.nodes('/letter/mainTerm') PropertyFeed(p)


SELECT *
FROM dbo.TestXML

请参阅SQLFiddle上的示例

于 2013-06-23T08:19:35.107 回答