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
在我的安裝中,別名「T(N)」和「T.N」無法識別。 – Glenn
這似乎可以工作,但僅限於一條記錄。我想查詢整個表格。 – Eric
有沒有比循環遍歷每條記錄更簡單的方法? – Eric