在 SQL 服务器函数中使用 OPENXML 函数的方法?

Way to use OPENXML function in SQL Server function?

我需要在 SQL 服务器函数中使用 OPENXML 函数,但函数中不允许使用存储过程。结果,我无法使用 sp_xml_preparedocument 获取文档句柄,因此我无法使用 OPENXML 函数。

所以我的问题是,除了 将我的函数转换为存储过程之外,还有什么方法可以在函数 中使用 OPENXML 吗?

根据 Microsoft 文档 (https://docs.microsoft.com/en-us/sql/t-sql/functions/openxml-transact-sql?view=sql-server-ver15),您必须将 docId 传递给 OPENXML,这是 sp_xml_preparedocument 的输出参数。因此与OPENXMLsp_xml_preparedocument存在相关性。

试试这个 http://codegumbo.com/index.php/2013/09/30/sql-server-xquery-nodes-method/ https://blog.sqlauthority.com/2016/05/19/sql-server-handling-xml-documents-notes-field-125/

你不需要OPENXML。您可以在 XML 数据类型上使用节点方法并在 XML 上进行解析。 MSDN Reference

Scenarios for using the nodes() method are the same as for using OPENXML (Transact-SQL), which provides a rowset view of the XML. However, you don't have to use cursors when you use the nodes() method on a table that contains several rows of XML documents.

DECLARE @location xml = '<root>  
  <Location LocationID="10">  
     <step>1</step>  
  </Location>  
  <Location LocationID="20">  
     <step>2</step>  
  </Location> 
  </root>'


CREATE FUNCTION ReturnStep (@location xml)
RETURNS TABLE
AS
RETURN
SELECT t.value('.','int') as stepnumber
FROM @location.nodes('/root/Location/step') as loc(t)

SELECT * FROM dbo.ReturnStep(@location)
+------------+
| stepnumber |
+------------+
|          1 |
|          2 |
+------------+