如何提取XML节点值?

时间:2019-04-17 06:09:08

标签: sql xml xquery xmlnode xquery-sql

我正在尝试创建一个SQL函数,该函数通过读取xmlNode返回所有月份的逗号分隔值,这些值具有true。

但是,我根本无法导航到months节点。

在路径中添加名称空间并没有帮助我从Node.Data中提取值

对于第一个节点(StartDateTime),我能够在相似的行上提取值(通过将路径用作

  

/ ScheduleDefinition / StartDateTime

请参考以下代码:

CREATE FUNCTION [dbo].[GetMonthsFromXML] 
(
    -- Add the parameters for the function here
    @xmlText NTEXT
)
RETURNS VARCHAR(MAX)
AS
BEGIN
/*
<ScheduleDefinition>
<StartDateTime>04/10/2019 06:00:00</StartDateTime>
<MonthlyRecurrence xmlns="http://schemas.microsoft.com/sqlserver/reporting/2010/03/01/ReportServer">
<Days>29</Days>
<MonthsOfYear>
<January>true</January>
<February>false</February>
<March>true</March>
<April>true</April>
<May>false</May>
<June>false</June>
<July>false</July>
<August>false</August>
<September>false</September>
<October>false</October>
<November>false</November>
<December>false</December>
</MonthsOfYear>
</MonthlyRecurrence>
</ScheduleDefinition>
*/
DECLARE @resultVar VARCHAR(MAX)
DECLARE @x xml
SET @x = CAST(@xmlText AS XML); 


;with cte 
as
(
SELECT 
    [MonthName] = Node.Data.value('local-name(.)', 'VARCHAR(20)')
    ,MonthValue = Node.Data.value('(.)[1]', 'VARCHAR(20)') 
FROM    
    @x.nodes('/ScheduleDefinition/MonthlyRecurrence/MonthsOfYear') Node(Data) 
 )
 select @resultVar = ISNULL( MAX(MonthValue),'') from cte; --where MonthValue is not null and MonthValue <> ''   ;

-- Return the result of the function
RETURN @resultVar

END
GO

1月,3月,4月是上述xml的预期输出

1 个答案:

答案 0 :(得分:0)

请参见https://docs.microsoft.com/en-us/sql/relational-databases/xml/add-namespaces-to-queries-with-with-xmlnamespaces?view=sql-server-2017,大致类似

WITH XMLNAMESPACES ( 'http://schemas.microsoft.com/sqlserver/reporting/2010/03/01/ReportServer' as rs)

SELECT 
    [MonthName] = Node.Data.value('local-name(.)', 'VARCHAR(20)')
    ,MonthValue = Node.Data.value('string(.)', 'VARCHAR(20)') 
FROM    
    @x.nodes('/ScheduleDefinition/rs:MonthlyRecurrence/rs:MonthsOfYear/rs:*[. = "true"]') Node(Data)