3

In SQL Server 2008.

I need execute a query like that:

DECLARE @x AS xml
SET @x=N'<r><c>First Text</c></r><r><c>Other Text</c></r>'
SELECT @x.query('fn:max(r/c)')

But return nothing (apparently because convert xdt:untypedAtomic to numeric)

How to "cast" r/c to varchar?

Something like

SELECT @x.query('fn:max(«CAST(r/c «AS varchar(20))»)')

Edit: Using Nodes the function MAX is from T-SQL no fn:max function In this code:

DECLARE @x xml;
SET @x = '';
SELECT @x.query('fn:max((1, 2))');
SELECT @x.query('fn:max(("First Text", "Other Text"))');

both query return expected: 2 and "Other Text" fn:max can evaluate string expression ad hoc. But the first query dont work. How to force string arguments to fn:max?

4

2 回答 2

3

This will perform the aggregate max function in T-SQL:

DECLARE @x AS xml
 SET @x=N'<r><c>First Text</c></r><r><c>Other Text</c></r>'

  SELECT 
  MAX(r.value('.','varchar(25)'))
  FROM @x.nodes('/r/c') r([r])

Returns

Other Text

After your update, I think I better understand your question. Unfortunately It looks like this may not be doable in MS SQL Server 2008 R2.

DECLARE @x AS xml
SET @x=N'<r><c>First Text</c></r><r><c>Other Text</c></r>'
SELECT @x.query('fn:max(xs:string(r/c))') 

Yields the error:

Msg 2365, Level 16, State 1, Line 3
XQuery [query()]: Cannot explicitly convert from 'xdt:untypedAtomic *' to 'xs:string'

According to Microsoft the type cast is valid, but I haven't been able to find a syntax that will work.

于 2010-12-23T17:18:57.027 回答
3
DECLARE @x AS xml
    , @val nvarchar(100) = 'Other Text'
SET @x=N'<r><c>First Text</c></r><r><c>Other Text</c></r>'
SELECT @x.query('fn:max(for $r in //r return xs:string ($r))')
于 2012-02-24T23:32:40.353 回答