检索与XML数据类型上的指定模式匹配的数据

时间:2015-04-02 04:48:07

标签: xml

如何检索所有LastNames,例如'%e%' ?

必需的输出

Desai, Pandey

我的XML:

DECLARE @MyXml XML  --declaring a variable of XML Datatype
SET @MyXml=' <Employees>
   <Employee>
      <Empid Status="On Vacation">1</Empid>
      <FirstName>Tejas</FirstName>
      <LastName>Desai</LastName>
      <Age>21</Age>
   </Employee>
   <Employee>
      <Empid Status="Active">2</Empid>
      <FirstName>Manohar</FirstName>
      <LastName>Pandey</LastName>
      <Age>34</Age>
   </Employee>
   <Employee>
      <Empid Status="Left">3</Empid>
      <FirstName>Anis</FirstName>
      <LastName>Shaikh</LastName>
      <Age>45</Age> </Employee>
</Employees>'

已为变量分配了三行,每行有四个列值

需要显示与模式匹配的所有名称=&#39;%e%&#39;

以下查询抛出错误

select @MyXml.query ('data(/Employees/Employee[@FirstName like '%e%'])') 

1 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

-- define a CTE to extract the relevant info from the <Employee> nodes
;WITH XmlCte AS 
(
    SELECT
        EmpId = XC.value('(Empid)[1]', 'int'),
        FirstName = XC.value('(FirstName)[1]', 'varchar(50)'),
        LastName = XC.value('(LastName)[1]', 'varchar(50)'),
        Age = XC.value('(Age)[1]', 'int')
    FROM
        @myxml.nodes('/Employees/Employee') AS XT(XC)
)
-- select from that CTE and get those employees with a 'e' in their last name
SELECT *
FROM XmlCte
WHERE LastName LIKE '%e%'

或者,如果您希望员工的名字包含e,请使用:

SELECT *
FROM XmlCte
WHERE FirstName LIKE '%e%'