如何遍历xml变量的所有行

时间:2011-04-05 13:35:09

标签: sql sql-server-2005 tsql

我有一个像

这样的xml变量
declare @xmlvar xml
create table tempxml(col1 xml)
insert into tempxml
exec someproc

select * from tempxml

此代码后tempxml包含数据:

<row eid="1" ename="jason" />
<row eid="2" ename="mike" />
<row eid="3" ename="ron" />

现在我想迭代一个循环并为每一行获取eid,并且需要以eid作为参数调用存储过程。即我需要做这样的事情

// Dummy code
While eid is not null
 // fetch eid from xml 
 exec somesp @eid = eid
Next

2 个答案:

答案 0 :(得分:2)

declare @xml xml = 
'<row eid="1" ename="jason" />
 <row eid="2" ename="mike" />
 <row eid="3" ename="ron" />'

-- @T table to hold the eid's from the xml
declare @T table (ID int identity, eid int)

insert into @T
select
  r.value('@eid', 'int')
from @xml.nodes('row') n(r) 

declare @eid int
declare @CurrentID int = 1

-- Fetch first eid
select @eid = eid
from @T
where ID = @CurrentID

while @@rowcount = 1
begin
  --exec SP with @eid here

  --Fetch next eid
  set @CurrentID = @CurrentID + 1

  select @eid = eid
  from @T
  where ID = @CurrentID
end 

答案 1 :(得分:1)

您可以尝试这样的事情:

-- declare table variable
DECLARE @EIDTable TABLE (RowEID INT)

-- fill table variable from XML variable
INSERT INTO @EIDTable(RowEID)
    SELECT
         row.value('(@eid)[1]', 'int')
    from 
         @xmlvar.nodes('/row') AS XmlRow(ROW)

-- declare single EID to process            
DECLARE @EID INT

-- fill single EID    
SELECT TOP  1 @EID = RowEID FROM @inputtable

-- loop while not NULL
WHILE @eid IS NOT NULL
BEGIN
    -- execute your stored procedure here with @eid as a parameter

    -- remove that EID that's been processed
    DELETE FROM @inputtable
    WHERE RowEID = @eid

    -- grab next EID from temporary table variable and loop    
    SET @EID = NULL
    SELECT TOP  1 @EID = RowEID FROM @inputtable
END