在SQL Server中迭代XML变量

前端之家收集整理的这篇文章主要介绍了在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
原文链接:https://www.f2er.com/mssql/84083.html

猜你在找的MsSQL相关文章