如何在表中插入n个xml节点

时间:2013-01-08 03:40:55

标签: sql sql-server xml

我的存储过程是这样的:

alter procedure insertxml
   @inxml xml
as

insert into imagess
  (ids, photo, names)
values 
  (@inxml.value('(/imagess/ids)[1]', 'int'),
   @inxml.value('(/imagess/photo)[1]', 'char'),
   @inxml.value('(/imagess/names)[1]', 'varchar(10)'))

exec insertxml '<imagess>
                  <ids>31</ids>
                  <photo>N</photo>
                  <names>30</names>
                  <ids>11</ids>
                  <photo>O</photo>
                  <names>20</names>
                  <ids>12</ids>
                  <photo>A</photo>
                  <names>43</names>
                </imagess>'

通过这个,我只能插入第一行。我想插入所有3行。

1 个答案:

答案 0 :(得分:2)

正如OMG Ponies在他的评论中指出的那样,需要调整XML代码才能使其工作;但是,我认为您正在寻找的是(注意XML中的附加标记):

DECLARE @imagess TABLE (ids INT, photo VARCHAR(1), NAMES INT)
DECLARE @inxml XML = '<imagess>
                  <image><ids>31</ids>
                  <photo>N</photo>
                  <names>30</names>
                  </image><image>
                  <ids>11</ids>
                  <photo>O</photo>
                  <names>20</names>
                  </image><image>
                  <ids>12</ids>
                  <photo>A</photo>
                  <names>43</names>
                  </image>
                </imagess>'


insert into @imagess
  (ids, photo, names)
SELECT c.value('(./ids)[1]', 'int'),
   c.value('(./photo)[1]', 'char'),
   c.value('(./names)[1]', 'varchar(10)')
FROM @inxml.nodes('//image') T(c)

SELECT *
FROM @imagess