简体   繁体   English

从SQL SELECT中的XML字符串中提取元素值

[英]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. 我正在尝试从SQL查询中提取XML字符串中元素的值。 In the code below, OPDV.DialValue returns the XML string with the element I want to retrieve. 在下面的代码中,OPDV.DialValue返回带有要检索的元素的XML字符串。

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. 这将返回下面的XML。 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. 我需要从FriendlyDisplay中提取数据。 I can parse the XML with the code below. 我可以用下面的代码解析XML。 This will return 4/3/2018 10:00 AM . 这将在2018年4月3日10:00 AM返回。

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. 我尝试使用子查询将XML字符串中的OPDV.DialValue替换为FriendlyValue,但没有任何效果。 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. SQL用于在Web应用程序中执行的功能。 Is there a way to extract the text from FriendlyValue? 有没有办法从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? 如果我理解您的要求,那么您将尝试从XML中获取一个值并将其设置为变量。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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