Query XML data in a function with namespace

丶灬走出姿态 提交于 2019-12-11 22:19:24

问题


I am facing problems while retrieving data from XML.

with xmlnamespaces ('x-elements' as x)
select 
tb.[Profile].value('(x:ppr/x:static/refId)[1]', 'varchar(22)') testCol
from table1 tb

The above code works perfectly fine. But, when I pass the XML path in a function it compiles correctly but doesn't return data upon calling but just the xml path (that is passed to it).

CREATE FUNCTION testFunc
(
    @p varchar(22)
)
RETURNS nvarchar(max)
AS
BEGIN
    DECLARE @Rs nvarchar(max);
    with xmlnamespaces ('x-elements' as x)
    select 
        @Rs = tb.[Profile].value('(sql:variable("@p_path"))[1]', 'nvarchar(max)') 
    from table1 tb
    RETURN (@Rs)

END

The result I am getting is "x:ppr/x:sta" (which is a path not the value) whereas it should return a value like "aJxk9pGntc5V" Please suggest a solution!


回答1:


The parameter to the value() function has to be a string literal. You can not replace it with a variable/parameter that contains the XQuery you want to execute.

From value() Method (xml Data Type)

Syntax

value (XQuery, SQLType)

XQuery

Is the XQuery expression, a string literal, that retrieves data inside the XML instance.

Your attempt to use sql:variable("@p_path") will insert the value of @p_path as a string to the XQuery. It will not replace the entire XQuery expression. It will translate to something like value('("x:ppr/x:sta")', 'varchar(100)')



来源:https://stackoverflow.com/questions/25683412/query-xml-data-in-a-function-with-namespace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!