2

我有以下代码:

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

2 | 481411.jpg

但我想动态更改根元素,例如:

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

但是这段代码不起作用。

4

1 回答 1

0

使用星号代替双斜杠

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

于 2013-08-29T11:16:33.620 回答