sql - 遍历 SQL Server 中的 XML 变量

标签 sql sql-server xml sql-server-2008

我在存储过程(SQL Server 2008)中有一个 XML 变量,它的示例值为

<parent_node>
   <category>Low</category>
   <category>Medium</category>
   <category>High</category>
</parent_node>

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

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

  1. 循环从 xml 变量中获取单个类别。
  2. 使用当前类别调用存储过程。
  3. 移至下一类别。
  4. 循环直到列表包含值。

我们将不胜感激。

最佳答案

是这样的吗?

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

关于sql - 遍历 SQL Server 中的 XML 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16499268/

相关文章:

sql - 如何在 SQL Server 2012 中生成特定查询

xml - Perl 通过 HTTP 解析 XML 文件并增加几行

minOccurs ="0"元素上的 C# XSD 验证失败

sql-server - 如何从 XML 数据形成 where 子句

sql - 使用 T-SQL 查找特定年份任何 ISO 周内的订单

java - 安卓资源命名空间

mysql - 插入行导致 404

sql - Oracle:使用 'order by' 子句显示行号

java - 提高 Primefaces 数据表性能

asp.net - 请求“System.Data.SqlClient.SqlClientPermission”类型的权限失败