微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在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.jb51.cc/mssql/84083.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐