I have fetch the data based on specific condition from the XML value. Idea is to have one table with two columns ID and Data(XML dataType). I have to fetch the data for specific ID.
Here is the example and I wish to achieve the result as only first row with Sears Tower ONLY. I am getting two rows.
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>
</B开发者_JAVA技巧uilding>
</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
Use:
DriverDetails/DriverDetail[ID eq 1]/*[not(self::ID)]
or, if you consider this simpler:
DriverDetails/DriverDetail[ID eq 1]/(PRN | Name))
Here it is assumed that (for both XPath expressions) the expression is evaluated having as initial context node the parent of DriverDetails
.
Got the answer. This should be like:
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
I am not sure if this is the better way or there is any other way to achieve this.
精彩评论