2015-04-02 63 views
-2

如何檢索所有LastNames(如'%e%')?檢索符合XML數據類型指定模式的數據

所需的輸出

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>' 

三排已經被分配給變量每個具有四個列的值

需要顯示所有符合該模式的名字='%e%'

以下查詢引發錯誤

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

好,***什麼* **錯誤是否會導致您的查詢?請發佈完整且準確的錯誤!我們真的無法讀取你的屏幕 - 也沒有你的想法.... – 2015-04-02 05:13:21

+0

另外:如果你檢查** FirstName **包含一個'e' - 你的結果將只是'Tejas' - 對嗎? – 2015-04-02 05:17:02

回答

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%'