XML 节点中的 SQL 变量

2021-09-16 00:00:00 xml sql variables sql-server xmlnode

我有以下代码:

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)

结果:

1 |4814111.jpg

1 | 4814111.jpg

2 |481411.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.

推荐答案

使用星号代替双斜线

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)

查看 SQLFiddle

相关文章