2

I have the following code:

DECLARE @x TABLE (item XML (document Galeries))
DECLARE  @schemaname     VARCHAR(100)
SET @schemaname  = 'GaleriesSchem2'

INSERT into @x
SELECT  '
<GaleriesSchem2>
  <Image_1 OriginalName="Image">4814111.jpg</Image_1>
  <Image_2 OriginalName="Image2">481411.jpg</Image_2>
</GaleriesSchem2>'

SELECT rref.value('.', 'varchar(MAX)') AS 'Value'
FROM @x
  CROSS APPLY   
    item.nodes('//GaleriesSchem2/node()') AS Results(rref)

result:

1 | 4814111.jpg

2 | 481411.jpg

But I want to change the root element dynamically, for example:

 item.nodes('//[local-name()=sql:variable("@schemaname")]/node()') AS Results(rref) 

But this code doesn't work.

1 Answer 1

0

Use asterisk instead of double slash

DECLARE @x TABLE(item XML)
DECLARE  @schemaname VARCHAR(100)
SET @schemaname = 'GaleriesSchem3'

INSERT into @x
SELECT  '
<GaleriesSchem2>
  <Image_1 OriginalName="Image">4814111.jpg</Image_1>
  <Image_2 OriginalName="Image2">481411.jpg</Image_2>
</GaleriesSchem2>
<GaleriesSchem3>
  <Image_1 OriginalName="Image">4814111_3.jpg</Image_1>
  <Image_2 OriginalName="Image2">481411_3.jpg</Image_2>
</GaleriesSchem3>
'
SELECT rref.value('.', 'varchar(MAX)') AS 'Value'
FROM @x
  CROSS APPLY     
    item.nodes('*[local-name()=sql:variable("@schemaname")]/node()') AS Results(rref)

See demo on SQLFiddle

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.