user2728832 user2728832 - 5 months ago 14
SQL Question

SQL Variable in XML Node

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.

Answer

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

Comments