在XML节点中使用sql:variable的语法错误SQL Server查询

时间:2019-05-21 12:32:18

标签: sql-server xml xquery-sql

我一直在研究从SQL Server数据库中提取XML数据的查询。我想从XML中提取特定的行。如果我在.nodes行中对ID进行硬编码,则可以按预期工作,但是当用sql:variable替换硬编码值并用尽我的Google-foo

时,我无法避免语法错误
'''SQL
DECLARE @XML XML = '<DynamicModel>
<AvailableElements>
  <Control Id="97a0d1c6-f2b4-4f6f-8d01-f6110f1679af">
  <Property Name="Name" Value="Picklist1" />
  <Property Name="Id" Value="97a0d1c6-f2b4-4f6f-8d01-f6110f1679af" />
  <Property Name="Label" Value="Label value here" />
  <Property Name="SelectedItemId" Value="Value in here" Type="System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" IsRequired="True" IsReference="True" />
  <Elements />
  <AvailableElements />
</Control>
</AvailableElements>
</DynamicModel>'
DECLARE @ElementID NVARCHAR(100) = '97a0d1c6-f2b4-4f6f-8d01-f6110f1679af'

/* WORKS */
SELECT
codedValue.value('@Name[1]', 'nvarchar(500)') AS ItemName,
codedValue.value('@Value[1]', 'nvarchar(500)') AS ItemValue
FROM @XML.nodes('/DynamicModel/AvailableElements/Control[@Id="97a0d1c6-f2b4-4f6f-8d01-f6110f1679af"]/Property') AS x(codedValue)
WHERE codedValue.value('@Name[1]', 'nvarchar(500)') IN ('Text','Date','SelectedItemId','Label')

/* DOES NOT WORK */
SELECT
codedValue.value('@Name[1]', 'nvarchar(500)') AS ItemName,
codedValue.value('@Value[1]', 'nvarchar(500)') AS ItemValue
FROM    @XML.nodes('/DynamicModel/AvailableElements/Control[@Id="sql:variable("@ElementID")]/Property') AS x(codedValue)
WHERE codedValue.value('@Name[1]', 'nvarchar(500)') IN ('Text','Date','SelectedItemId','Label')
'''

硬编码版本返回了两行,这基于XML是正确的。使用sql:variable的版本出现错误,并显示消息“ XQuery [nodes()]:'@'附近的语法错误,预期为']'。”

1 个答案:

答案 0 :(得分:0)

您的查询应该像这样-

SELECT
codedValue.value('@Name[1]', 'nvarchar(500)') AS ItemName,
codedValue.value('@Value[1]', 'nvarchar(500)') AS ItemValue
FROM    @XML.nodes('/DynamicModel/AvailableElements/Control[@Id=sql:variable("@ElementID")]/Property') AS x(codedValue)
WHERE codedValue.value('@Name[1]', 'nvarchar(500)') IN ('Text','Date','SelectedItemId','Label')