我正在寻找一种搜索sql xml列中所有节点的方法。
例如,如果我有以下XML
<ArrayOfEntityPropertyOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<EntityPropertyOfString>
<Name>User Label 1</Name>
<Value>TX 12107210</Value>
</EntityPropertyOfString>
<EntityPropertyOfString>
<Name>User Label 2</Name>
<Value>BONUS $350/DAY</Value>
</EntityPropertyOfString>
<EntityPropertyOfString>
<Name>User Defined Date 9</Name>
<Value>11/09/2011</Value>
</EntityPropertyOfString>
</ArrayOfEntityPropertyOfString>
如何搜索包含“bonus”一词的所有值?
提前谢谢。
答案 0 :(得分:5)
declare @xml xml =
'<ArrayOfEntityPropertyOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<EntityPropertyOfString>
<Name>User Label 1</Name>
<Value>TX 12107210</Value>
</EntityPropertyOfString>
<EntityPropertyOfString>
<Name>User Label 2</Name>
<Value>BONUS $350/DAY</Value>
</EntityPropertyOfString>
<EntityPropertyOfString>
<Name>User Defined Date 9</Name>
<Value>11/09/2011</Value>
</EntityPropertyOfString>
</ArrayOfEntityPropertyOfString>'
select T.N.value('local-name(.)', 'nvarchar(max)') as NodeName,
T.N.value('text()[1]', 'nvarchar(max)') as NodeValue
from @xml.nodes('//*') as T(N)
where T.N.value('text()[1]', 'nvarchar(max)') like '%bonus%'
结果:
NodeName NodeValue
-------------------- --------------------
Value BONUS $350/DAY
对于表格,它可能如下所示:
declare @T table (ID int identity primary key, XMLCol xml)
declare @xml xml =
'<ArrayOfEntityPropertyOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<EntityPropertyOfString>
<Name>User Label 1</Name>
<Value>TX 12107210</Value>
</EntityPropertyOfString>
<EntityPropertyOfString>
<Name>User Label 2</Name>
<Value>BONUS $350/DAY</Value>
</EntityPropertyOfString>
<EntityPropertyOfString>
<Name>User Defined Date 9</Name>
<Value>11/09/2011</Value>
</EntityPropertyOfString>
</ArrayOfEntityPropertyOfString>'
insert into @T values (@xml)
insert into @T values (@xml)
select T1.ID,
T2.N.value('local-name(.)', 'nvarchar(max)') as NodeName,
T2.N.value('text()[1]', 'nvarchar(max)') as NodeValue
from @T as T1
cross apply T1.XMLCol.nodes('//*') as T2(N)
where T2.N.value('text()[1]', 'nvarchar(max)') like '%bonus%'
结果:
ID NodeName NodeValue
----------- -------------------- --------------------
1 Value BONUS $350/DAY
2 Value BONUS $350/DAY
答案 1 :(得分:0)
如果您可以假设奖金永远不会出现在标签中......
SELECT
...
FROM
...
WHERE COL_NAME LIKE '%bonus%'