我有一个包含许多行的表,每个行都有一个名为“ RecordData”的列,其中包含我要搜索的XML数据。
下面给出了此列中三行示例xml数据的值:
1:
<Record> <RecordField ID="31" Name="Barcode1" DataTypeId="5" TypeName="String" Decimals="0" Format="" Mandatory="False">ABC123</RecordField> </Record>
2:
<Record> <RecordField ID="15" Name="Field 1" DataTypeId="7" TypeName="Boolean" Decimals="0" Format="" Mandatory="False">true</RecordField> <RecordField ID="16" Name="Field 2" DataTypeId="5" TypeName="String" Decimals="0" Format="" Mandatory="False">purpke</RecordField> </Record>
3:
<Record> <RecordField ID="15" Name="Field 1" DataTypeId="7" TypeName="Boolean" Decimals="0" Format="" Mandatory="False">true</RecordField> <RecordField ID="16" Name="Field 2" DataTypeId="5" TypeName="String" Decimals="0" Format="" Mandatory="False">12</RecordField> </Record>
我正在使用以下SQL尝试查找任何表行,这些表行的XML数据包含特定的搜索词(在本示例中为‘1’)。
DECLARE @SearchTerm varchar(max) SET @SearchTerm = '1' SELECT * FROM MyTableOfData WHERE RecordFields.value('contains( (/Record/RecordField/text())[1],sql:variable("@SearchTerm"))','bit') = 1
正如您将看到的,这依赖于出现在第一个“ RecordField”元素文本中的搜索词,而不是在所有“ RecordField”节点上进行搜索。意思是,我得到的唯一结果将是第1行,而不是第1行和第3行。
我已经阅读了有关MSDN的相关文章,并度过了Google失败的一天,因为我离寻找消除限制并最终破解它的距离越来越近了。
任何帮助将不胜感激 :)
编辑:
DECLARE @SearchTerm varchar(max) SET @SearchTerm = '1' select * from MyTableOfData cross apply MyTableOfData.RecordFields.nodes('/Record/RecordField') as tx(r) where tx.r.value('.','varchar(10)') like '%'+@searchterm+'%'
抛出:
Msg 493, Level 16, State 1, Line 3 The column 'r' that was returned from the nodes() method cannot be used directly. It can only be used with one of the four XML data type methods, exist(), nodes(), query(), and value(), or in IS NULL and IS NOT NULL checks.
编辑2:
当您准确复制所告知的内容时,它不会丢失任何东西,而是有效的!
DECLARE @SearchTerm varchar(max) SET @SearchTerm = '1' select MyTableOfData.* from MyTableOfData cross apply MyTableOfData.RecordFields.nodes('/Record/RecordField') as tx(r) where tx.r.value('.','varchar(10)') like '%'+@searchterm+'%'
CROSS APPLY 是您找不到的东西…
CROSS APPLY
select yourtable.* from yourtable cross apply yourtable.RecordFields.nodes('/Record/RecordField') as tx(r) where tx.r.value('.','varchar(10)') like '%'+@searchterm+'%'
或者
where tx.r.value('contains((.),sql:variable("@searchterm"))','bit')=1