2

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="[email protected]" />  
</RootEPS>

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

For an input email [email protected] I want an output like

fName  |  lName  | address1  |  email
Test   |  Singh  | 23 t-2    | [email protected]

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="[email protected]"]') AS N(x)

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

1 Answer 1

3

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)')
            = '[email protected]'

Working example at SE Data.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.