sql - 如何在 SQL Server 的存储过程中从 xml 节点创建游标?

标签 sql sql-server xml tsql stored-procedures

我将一个 XML 文档作为参数传递到我的存储过程。然后我试图填充游标以循环遍历 XML 的元素。我的问题是如何选择此 XML 文档的每个元素并用它们填充我的光标?

XML 文档

<Authors>
    <Author_id>1</Author_id>
    <Author_id>2</Author_id>
</Authors>

存储过程

CREATE PROCEDURE Insert_Publication
    @authors xml
AS

    DECLARE @id int

    DECLARE authors_cursor CURSOR FOR
    SELECT @authors.query('(/Authors/Author_id)') 

    open authors_cursor 

    FETCH NEXT FROM authors_cursor INTO @id

最佳答案

您可以使用 .nodes().value() :

DECLARE @authors XML = 
'<Authors>
    <Author_id>1</Author_id>
    <Author_id>2</Author_id>
</Authors>';

DECLARE @id INT;

DECLARE authors_cursor CURSOR FOR
SELECT n.c.value('.', 'INT') AS author_id
FROM @authors.nodes('/Authors/Author_id') AS n(c);

OPEN authors_cursor;

FETCH NEXT FROM authors_cursor INTO @id;

WHILE @@FETCH_STATUS = 0
BEGIN
  PRINT @id;                                -- do whatever you need with @id
  FETCH NEXT FROM authors_cursor INTO @id;
END

CLOSE authors_cursor;
DEALLOCATE authors_cursor; 

LiveDemo

工作原理:

DECLARE authors_cursor CURSOR FOR
SELECT n.c.value('.', 'INT') AS author_id
FROM @authors.nodes('/Authors/Author_id') AS n(c);
  1. @authors.nodes('/Authors/Author_id') 获取基于 XQuery 的节点和派生表的别名 nc - 用于列

  2. 使用n.c.value('.', 'INT') AS author_id获取元素的实际值

关于sql - 如何在 SQL Server 的存储过程中从 xml 节点创建游标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34565965/

相关文章:

mysql - where 子句中的动态参数

mysql - 对同一列进行多次计数并插入到另一个表中

sql - sql server存储过程中的多个表类型参数

带有存储过程的 SQL Server openquery() 不返回数据

php - MySQL,检查结果是否有值(value),如果没有则取另一个

php - SQL 运算符 : AND and OR

sql-server - 带附件的数据库电子邮件(excel 文件/pdf 文件)?

xml - python解析xml并获取root下每个子元素的属性值

java - 使用 XML 简单框架反序列化包含 CDATA 的元素列表

java - 如何在没有标记值的情况下将映射编码为 xml