views:

60

answers:

1

According to BOL on value() Method (xml Data Type),

value() method takes two arguments

  • XQuery
  • SQLType

Do I need to pass varchar or nvarchar to value()? How can I find out what kind of type XQuery or SQLType expects?

End Goal: To create utility UDF/sprocs that uses XML Data Type methods.

+1  A: 

It works with both:

WITH    q AS
        (
        SELECT  CAST('<root><node>1</node></root>' AS XML) AS doc
        )
SELECT  doc.value('(/root/node)[1]', 'INT'),
        doc.value(N'(/root/node)[1]', 'INT')
FROM    q

Note that the XQuery is compiled during the parsing stage, i. e. you can supply only the string literal as first argument (not a column, expression or a variable).

This string literal has no "type", since type assumes a set of possible values that are known only at runtime, and XML functions accept only literal XQuery expressions which should be known at compile time.

You cannot pass them from the arguments or your functions or as variables, you can only hardcode them into the query.

Treat them as reserved words (like SELECT or UPDATE), which for some reason should be enclosed into single quotes.

You should build the whole query dynamically if you want the XQuery to be dynamic.

Quassnoi
I am quite shocked that I cannot pass an XQuery value as a parameter but only as a 'string literal'...
Sung Meister
@Sung Meister: they don't expect "type", they expect a set of reserved words enclosed into single quotes, optionally prepended with `N`. Don't be fooled by the fact that it looks like a `VARCHAR` or `NVARCHAR`: it is neither of them.
Quassnoi
It looks like BOL is quite misleading on XQuery parameter description - "Is a string , an XQuery expression...". They don't mention anything about XML Data methods expecting "a set of reserved words enclosed into single quotes"
Sung Meister
@Sung Meister: From the link you provided: *`XQuery`: is the `XQuery` expression, a string literal, that retrieves data inside the `XML` instance*. They state that it should be a literal, and the error message states the same.
Quassnoi
Maybe I was lacking knowledge on "string literal" meant. Thank you for clearing that confusion for me.
Sung Meister