简体   繁体   中英

XPATH query in SQL Server for an XML type column

I have a table 'TEST', It has a column 'info' of type xml. Column info has XML like

<RootEPS xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <EPS key="FirstName" value="Test" />
   <EPS key="LastName" value="Singh" />
   <EPS key="address1" value="23 t-2" />
   <EPS key="EmailAddress" value="test.singh@gmail.com" />  
</RootEPS>

I want to create a XPATH sql query to get the data of attribute 'value' of each EPS node eg firstName as fName, lastName as lName based on given email.

For an input email test.singh@gmail.com I want an output like

fName  |  lName  | address1  |  email
Test   |  Singh  | 23 t-2    | test.singh@gmail.com

I am trying something like this but it's not working

SELECT distinct
  N.x.value('@value', 'nvarchar(100)') as fName,
  N.x.value('@value', 'nvarchar(100)') as lName,
  N.x.value('@value', 'nvarchar(100)') as address1,
  N.x.value('@value', 'nvarchar(100)') as email,
FROM
  TEST AS RO
   CROSS APPLY
   RO.info.nodes('/RootEPS/EPS[@key="EmailAddress" and @value="test.singh@gmail.com"]') AS N(x)

In output I am getting only email value. Mainly having issue in Nxvalue('@value' part.

You're selecting a single EPS node. Use values on the entire RootEPS node and you can query all of its EPS children:

SELECT  info.value('(RootEPS/EPS[@key="FirstName"]/@value)[1]', 'nvarchar(100)') as fName
,       info.value('(RootEPS/EPS[@key="LastName"]/@value)[1]', 'nvarchar(100)') as lName
,       info.value('(RootEPS/EPS[@key="address1"]/@value)[1]', 'nvarchar(100)') as address1
,       info.value('(RootEPS/EPS[@key="EmailAddress"]/@value)[1]', 'nvarchar(100)') 
            as email
FROM    TEST
WHERE   info.value('(RootEPS/EPS[@key="EmailAddress"]/@value)[1]', 'nvarchar(100)')
            = 'test.singh@gmail.com'

Working example at SE Data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM