0

I know how to select a value from an XML field using xpath and defining namespaces, but I need to use several xpath queries and assign them to my selection. Is there an easier way than doing the following:

SELECT 
    id, name,
    [XML].value('declare namespace test="http://www.test.org/xml/";
                 declare namespace test2="http://www.test2.org";
                 (//test:Address[1][test2:Global=1]/test:Street)[1] ', 'varchar(max)') AS streetLocation1,
    [XML].value('declare namespace test="http://www.test.org/xml/";
                 declare namespace test2="http://www.test2.org";
                 (//test:Address[2][test2:Global=1]/test:Street)[1] ', 'varchar(max)') AS streetLocation2 
FROM  
    TEST

I want to replace

'declare namespace test="http://www.test.org/xml/";
 declare namespace test2="http://www.test2.org";'

by using a variable. I tried to append strings but I got the following:

The argument 1 of the XML data type method "value" must be a string literal.

There has to be an easier way.

Thanks,

-James

1
  • 2
    Have a look at with xmlnamespaces. You can't use variables in there but you only have to declare the namespaces once for the entire query. Commented Sep 24, 2012 at 20:50

1 Answer 1

1

Thanks @MikaelEriksson,

In case anyone has a similar issues. Here is the answer.

;WITH XMLNAMESPACES ('http://www.test.org/xml/' as test, 'http://www.test.org/xml/' as test2)
SELECT id,
       name,
       [XML].value('(//test:Address[1][test2:Global=1]/test:Street)[1] ', 'varchar(max)') AS streetLocation1,
       [XML].value('(//test:Address[2][test2:Global=1]/test:Street)[1] ', 'varchar(max)') AS streetLocation2 
FROM  TEST
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.