简体   繁体   中英

Extracting Element Value from XML String in SQL SELECT

I'm trying to extract the value of an element in an XML string from a SQL query. In the code below, OPDV.DialValue returns the XML string with the element I want to retrieve.

select OPDV.DialValue as DueDate           -- DialValue returns an XML string
from Orders O

join OrderProduct OP
    on OP.OrderID = O.OrderID

join OrderProductDialValue OPDV
    on OPDV.OrderProductID = OP.OrderProductID

join Dial_Culture DC
    on DC.DialID = OPDV.DialID

join Users U
    on U.UserID = O.CustomerID

where (O.OrderId = @OrderId) and (DC.FriendlyName = 'Due Date & Time')

This returns the XML below. I had to include comments in the code here because the tags disappear and only show the data.

<!--<DateTime><Server>03/04/2018 10:00:03</Server><Client>03/04/2018 10:00:00</Client><FriendlyDisplay>4/3/2018 10:00 AM</FriendlyDisplay></DateTime>-->

I need to extract the data from FriendlyDisplay. I can parse the XML with the code below. This will return . 返回。

DECLARE @form XML = '<DateTime><Server>03/04/2018 10:00:03</Server><Client>03/04/2018 10:00:00</Client><FriendlyDisplay>4/3/2018 10:00 AM</FriendlyDisplay></DateTime>'

SELECT a.b.value('FriendlyDisplay[1]', 'varchar(100)')
    FROM @form.nodes('DateTime') a(b) 

I've tried playing with subqueries to replace the OPDV.DialValue with FriendlyValue in the XML string, but nothing has worked. I can't declare a variable in a subquery, ie

select (declare @form xml=OPDV.DialValue; select ... )

The SQL is for a function that is executed in the web application. Is there a way to extract the text from FriendlyValue?

Thanks.

If I understand what you're asking... You're trying to take a value from the XML and set it as a variable... So, something like the following?

DECLARE @form XML = '<DateTime><Server>03/04/2018 10:00:03</Server><Client>03/04/2018 10:00:00</Client><FriendlyDisplay>4/3/2018 10:00 AM</FriendlyDisplay></DateTime>'

DECLARE @MyDate DATETIME

SELECT @MyDate = a.b.value('FriendlyDisplay[1]', 'varchar(100)')
    FROM @form.nodes('DateTime') a(b) 

SELECT * FROM sometable WHERE someDate = @MyDate

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