在SQL Server中迭代XML变量

我在存储过程(sql Server 2008)中有一个XML变量,其示例值为
<parent_node>
   <category>Low</category>
   <category>Medium</category>
   <category>High</category>
</parent_node>

我必须将每个类别作为单独的记录插入表中.如何迭代XML并获取单个节点值?

如果我想调用存储过程并将每个类别作为输入参数发送,我们该怎么做?存储过程是遗留过程,它一次只接受一个类别.我试图以这种方式调用程序.

>循环从xml变量中获取单个类别.
>使用当前类别调用存储过程.
>转到下一个类别.
>循环直到列表包含值.

任何帮助将不胜感激.

解决方法

像这样的东西?
DECLARE @XmlVariable XML = '<parent_node>
                              <category>Low</category>
                              <category>Medium</category>
                              <category>High</category>
                            </parent_node>'

INSERT INTO dbo.YourTargetTable(CategoryColumn)
  SELECT 
     XTbl.Cats.value('.','varchar(50)')
  FROM 
     @XmlVariable.nodes('/parent_node/category') AS XTbl(Cats)

更新:如果你必须使用旧的遗留存储过程并且不能改变它(这是我这样做的首选方式),那么你必须自己进行逐行(RBAR)循环,例如:通过使用表变量:

-- declare temporary work table
DECLARE @RbarTable TABLE (CategoryName VARCHAR(50))

-- insert values into temporary work table
INSERT INTO @RbarTable(CategoryName)
  SELECT 
     XTbl.Cats.value('.','varchar(50)')
  FROM 
     @XmlVariable.nodes('/parent_node/category') AS XTbl(Cats)

-- declare a single category
DECLARE @CategoryNametoBeInserted VARCHAR(50)

-- get the first category
SELECT TOP 1 @CategoryNametoBeInserted = CategoryName FROM @RbarTable

-- as long as we have data
WHILE @CategoryNametoBeInserted IS NOT NULL
BEGIN
    -- execute your stored procedure here.....    
    EXEC sp_executesql N'dbo.YourStoredProcedure @CategoryName',N'@CategoryName VARCHAR(50)',@CategoryName = @CategoryNametoBeInserted

    -- delete the category we just inserted from the temporary work table
    DELETE FROM @RbarTable WHERE CategoryName = @CategoryNametoBeInserted

    -- see if we still have more categories to insert    
    SET @CategoryNametoBeInserted = NULL
    SELECT TOP 1 @CategoryNametoBeInserted = CategoryName FROM @RbarTable ORDER BY CategoryName
END

相关文章

SELECT a.*,b.dp_name,c.pa_name,fm_name=(CASE WHEN a.fm_n...
if not exists(select name from syscolumns where name=&am...
select a.*,pano=a.pa_no,b.pa_name,f.dp_name,e.fw_state_n...
要在 SQL Server 2019 中设置定时自动重启,可以使用 Window...
您收到的错误消息表明数据库 &#39;EastRiver&#39; 的...
首先我需要查询出需要使用SQL Server Profiler跟踪的数据库标...