我根据XML值中的特定条件获取数据。 想法是让一个表具有两列ID和数据(XML dataType)。我必须获取特定ID的数据。
以下是示例,我希望仅将结果显示为Sears Tower的第一行。我有两排。
IF OBJECT_ID('tempdb..#ExistExample') IS NOT NULL
DROP TABLE #ExistExample
GO
CREATE TABLE #ExistExample
(
XMLID Int,
XMLDocument xml
)
INSERT INTO #ExistExample
VALUES (100,'<Buildings>
<Building>
<Name>Sears Tower</Name>
<Floor1>Yes</Floor1>
<Floor2>Yes</Floor2>
<Floor3>No</Floor3>
</Building>
<Building>
<Name>IDS Building</Name>
<Floor1>Yes</Floor1>
<Floor2>Yes</Floor2>
<Floor3>Yes</Floor3>
</Building>
</Buildings>')
DECLARE @data varchar(1000)
DECLARE @ID INT
SET @ID = 101
SET @data = 'Sears Tower'
INSERT INTO #ExistExample
VALUES (101,'<Buildings>
<Building>
<Name>Sears Tower</Name>
<Floor1>Yes</Floor1>
<Floor2>Yes</Floor2>
<Floor3>No</Floor3>
</Building>
<Building>
<Name>IDS Building</Name>
<Floor1>Yes</Floor1>
<Floor2>Yes</Floor2>
<Floor3>Yes</Floor3>
</Building>
</Buildings>')
--SELECT * FROM #ExistExample
SELECT
c.value('(Name/text())[1]','varchar(25)') AS BuildingName,
c.value('(Floor1/text())[1]','varchar(25)') AS Floor1,
c.value('(Floor2/text())[1]','varchar(25)') AS Floor2,
c.value('(Floor3/text())[1]','varchar(25)') AS Floor3
FROM #ExistExample
CROSS APPLY XMLDocument.nodes('/Buildings/Building') as t(c)
WHERE c.exist('//Building/Name[.=sql:variable("@data")]') = 1
AND XMLID = @ID
答案 0 :(得分:1)
使用强>:
DriverDetails/DriverDetail[ID eq 1]/*[not(self::ID)]
或者,如果你认为这更简单:
DriverDetails/DriverDetail[ID eq 1]/(PRN | Name))
这里假设(对于两个XPath表达式)表达式被评估为具有DriverDetails
的父对象的初始上下文节点。
答案 1 :(得分:0)
得到了答案。这应该是:
SELECT c.value('(Name/text())[1]','varchar(25)') AS BuildingName,
c.value('(Floor1/text())[1]','varchar(25)') AS Floor1,
c.value('(Floor2/text())[1]','varchar(25)') AS Floor2,
c.value('(Floor3/text())[1]','varchar(25)') AS Floor3
FROM #ExistExample
CROSS APPLY XMLDocument.nodes('/Buildings/Building') as t(c)
WHERE c.value('(Name/text())[1]','varchar(25)') = @data
AND XMLID = @ID
我不确定这是否是更好的方法,或者还有其他方法可以实现这一点。