Argument 1 of the value method of the XML data type must be a string literal

I read SO: A data method like XML XML should be a string literal , but my problem is a little different. I have a little xml in a variable that I want to split, and they gave me a path. I originally tried this:

declare @x xml
select @x = '....'
select @x.value('(' + @path + ')[1]', 'varchar(max)')

but of course it fails. then I found the sql: variable and tried this:

select @x.value('(sql:variable("@path"))[1]', 'varchar(max)')

but this curiously returns @path (why?). I was messing with him, but I can't get him to do the right thing.

Anyone's thoughts?

+5
source share
3 answers

wBob Microsoft, . , , , , :)

if object_id('VMConfigVal') is not null
drop function VMConfigVal
go
create function VMConfigVal(@x xml, @path varchar(max))
returns nvarchar(max)
as
begin
    declare @ret nvarchar(max)

    ;with cte as
    (
    select  value = x.c.value('.', 'varchar(50)')
    ,       path = cast ( null as varchar(max) )
    ,       node = x.c.query('.')
    from    @x.nodes('/*') x(c)
    union all
    select  n.c.value('.', 'varchar(50)')
    ,       isnull( c.path + '/', '/' )
        +       n.c.value('local-name(.)', 'varchar(max)')
    ,       n.c.query('*')
    from    cte c
    cross   apply c.node.nodes('*') n(c)
    )
    select @ret = value from cte where path = @path
    return @ret
    end
go

- :

select dbo.VMConfigVal(MyXMLConfig, '/hardware/devices/IDE/ChannelCount')
from someTable

!

+2

@path, sql:variable() , SQL- @path , . , , , , SQL, :

declare @xml xml = '
<root>
    <element attr="test">blah</element>
</root>';

declare @p nvarchar(max) = '(//element/text())[1]';
declare @sql nvarchar(max) 
    = 'select @x.value(''' + @p + ''', ''nvarchar(max)'')';

exec sp_executesql @sql, @parameters = N'@x xml', @x = @xml;

, ( SQL-, ..)

+3

If you only need to find the child by name and want to abstract the name from the XPath literal, here are a few options:

// Returns the /root/node/element/@Value with @Name contained in @AttributeName SQL variable.
SELECT @Xml.value('(/root/node/element[@Name=sql:variable("@AttributeName")]/@Value)[1]', 'varchar(100)')

// Returns the text of the child element of /root/node with the name contained in @ElementName SQL variable.
SELECT @Xml.value('(/root/node/*[name(.)=sql:variable("@ElementName")]/text())[1]', 'varchar(100)')

// Searching the xml hierarchy for elements with the name contained in @ElementName and returning the text().
SELECT @Xml.value('(//*[name(.)=sql:variable("@ElementName")]/text())[1]', 'varchar(100)')

You need to declare the @ElementName or @AttributeName SQL variable to run them. I checked the first statement, but did not explicitly check the other 2 statements, FYI.

+1
source

All Articles