在SQL Server中迭代XML变量
发布时间:2021-03-06 18:04:20 所属栏目:MsSql教程 来源:网络整理
导读:我在存储过程(SQL Server 2008)中有一个XML变量,其示例值为 parent_node categoryLow/category categoryMedium/category categoryHigh/category/parent_node 我必须将每个类别作为单独的记录插入表中.如何迭代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 (编辑:淮安站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
站长推荐
热点阅读