sql-server - 将xml数据加载到SQL Server 2012中的表中

标签 sql-server t-sql

我有一个如下的 XML。我正在尝试使用 t-sql 代码将该 xml 加载到 SQL Server 表中: XML:

<Validations>
    <Validation>
    <validation id="ActivityIdPass" status="Fail">An Activity ID must be defined.</validation>
    <validation id="ActivityFormatPass" status="Pass">Passed</validation>
    <validation id="ActivityFormatSubCatPass" status="Pass">Passed</validation>
    <validation id="StartDateTimePass" status="Fail">A Release Date must be defined</validation>
    <validation id="EndDateTimePass" status="Fail">A Expiration Date must be defined.</validation>
    <validation id="CityPass" status="Pass">Passed</validation>
    <validation id="State" status="Pass">Passed</validation>
    </Validation>
</Validations>

我试图在加载到表中时获得以下输出:

image2

谁能帮帮我。

最佳答案

您可以使用OPENXML .

已关注 Arshad Ali's示例:

Process XML data using OPENXML function

Now as I said before, XML data stored in a column of data type XML can be processed either by using XML functions available in SQL Server or by using the sp_xml_preparedocument stored procedure along with the OPENXML function.

We will first call the sp_xml_preparedocument stored procedure by specifying the XML data which will then output the handle of the XML data that it has prepared and stored in internal cache.

Then we will use the handle returned by the sp_xml_preparedocument stored procedure in the OPENXML function to open the XML data and read it.

Note: the sp_xml_preparedocument stored procedure stores the XML data in SQL Server's internal cache, it is essential to release this stored XML data from internal cache by calling the sp_xml_removedocument stored procedure. We should call the sp_xml_removedocument stored procedure as early possible, so that internal cache can be freed for other usage.

USE OPENXMLTesting
GO

DECLARE @XML AS XML, @hDoc AS INT, @SQL NVARCHAR (MAX)

SELECT @XML = XMLData FROM XMLwithOpenXML

EXEC sp_xml_preparedocument @hDoc OUTPUT, @XML

SELECT CustomerID, CustomerName, Address
FROM OPENXML(@hDoc, 'ROOT/Customers/Customer')
WITH 
(
CustomerID [varchar](50) '@CustomerID',
CustomerName [varchar](100) '@CustomerName',
Address [varchar](100) 'Address'
)

EXEC sp_xml_removedocument @hDoc
GO

关于sql-server - 将xml数据加载到SQL Server 2012中的表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35463499/

相关文章:

sql-server - 优化删除大量外键引用的表

sql - 无限可选参数

sql-server - SSRS Report Builder 如何隐藏导出到 Excel 的特定文本框

sql-server - 如何获取字符串sql中某些字符之后的所有字符

sql - 否定sql中的 "unknown"值

sql-server - 如何将本地 Visual Studio mdf 数据库导出为 Azure SQL 数据库的格式

sql-server - 获取选定日期范围内的平均小时周期

sql - 查询包括子查询和分组比预期慢

sql-server - SQL Server 2005 : File Resizing

sql-server - 解析带有多个分隔符的整数值的 SQL 字符串