如何获取varchar(MAX)字符串类型的XML标签的值?

时间:2019-04-30 13:50:41

标签: sql sql-server xml tsql sql-server-2016

我正在使用SQL Server2016。

我有一个表 employee_xml ,该表的列 employee_xml_string varchar(MAX)类型。

CREATE TABLE employee_xml 
(
     employee_xml_id INT IDENTITY(1,1) NOT NULL, 
     employee_xml_string VARCHAR(MAX)
);

employee_xml_string列存储XML字符串;例如:

<?xml version="1.0" encoding="UTF-8"?>
<Employees xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <Employee>
      <EmployeeNumber>58913A</EmployeeNumber>
      <FirstName>Shanee</FirstName>
      <LastName>McKenzie</LastName>
      <GovernmentIdentificationNumber>749146551</GovernmentIdentificationNumber>
   </Employee>
</Employees>

我想编写SQL来获取<GovernmentIdentificationNumber>标签的值。我该怎么办?

谢谢

3 个答案:

答案 0 :(得分:3)

您必须将XML的值CAST / CONVERT设为xml(因此希望它们都是有效的XML值),然后您可以对它使用XQUERY转换后的值:

SELECT V.Employee_XML.value('(Employees/Employee/GovernmentIdentificationNumber/text())[1]','int') AS GovernmentIdentificationNumber
FROM dbo.employee_xml E
     CROSS APPLY (VALUES(TRY_CONVERT(xml,E.employee_xml_string))) V(Employee_XML);

但是,理想情况下,您应该将XML数据存储为xml;毕竟这就是它的目的。

答案 1 :(得分:2)

您可以使用nodes将xml切成一行,然后可以使用value选择正确的项目:

;with x as
(
    select cast(employee_xml_string as xml) as employee_xml
    from employee_xml
)
SELECT
    t.s.value('.', 'nvarchar(max)') AS GovernmentIdentificationNumber
FROM x
CROSS APPLY x.employee_xml.nodes('//Employees/Employee/GovernmentIdentificationNumber') t(s)

结果:

enter image description here

答案 2 :(得分:2)

您本可以将xml存储为XML。话虽如此,您可以随时对其进行投射:

SELECT employee_xml_xml.value('(/Employees/Employee/GovernmentIdentificationNumber)[1]', 'varchar(100)')
FROM employee_xml
CROSS APPLY (SELECT CAST(employee_xml_string AS xml)) AS x(employee_xml_xml)