Introduction: In this article i am going to explain
how to find all or specific records in sql table where the xml node's attribute
value matches with the variable value that we pass.
In previous articles i explained How to Concatenate rows values as a comma separated string using for xml path and stuff in sql server and Parse xml and get data as comma separated string format and Update multiple xml node values with new values in table and Select or read xml column data from table and Using case statement inside in clause (alternative)
Implementation: Let create a table variable for
demonstration purpose.
DECLARE
@Employee TABLE(Id
INT IDENTITY(1,1),empXML XML);
Let's insert some dummy data into this table.
INSERT INTO @Employee VALUES
(
'<ROOT>
<Employee Id="100"/>
<Employee Id="101"/>
<Employee Id="102"/>
</ROOT>'
)
INSERT INTO @Employee VALUES
(
'<ROOT>
<Employee Id="100"/>
<Employee Id="106"/>
<Employee Id="107"/>
</ROOT>'
)
INSERT INTO @Employee VALUES
(
'<ROOT>
<Employee Id="100"/>
<Employee Id="102"/>
<Employee Id="109"/>
</ROOT>'
)
INSERT INTO @Employee VALUES
(
'<ROOT>
<Employee Id="111"/>
<Employee Id="107"/>
<Employee Id="101"/>
</ROOT>'
)
Show table data
SELECT * FROM @Employee
Now suppose we want to find all the rows where
Employee Id=101 exists in empXML column.
DECLARE
@EmployeeId INT=101;
Then the Query will be as:
SELECT * FROM @Employee
WHERE empXML.exist('ROOT/Employee[@Id=sql:variable("@EmployeeId")]') = 1
Result will be as expected i.e.it will find all the
rows from table where Employee Id=101 exists :
Id
|
empXML
|
1
|
<ROOT><Employee
Id="100" /><Employee Id="101" /><Employee
Id="102" /></ROOT>
|
4
|
<ROOT><Employee
Id="111" /><Employee Id="107" /><Employee
Id="101" /></ROOT>
|
Now suppose we want to find only those records where
Employee Id=101 exists in empXML column and the value of the column Id=4. Then
the Query will be as:
SELECT * FROM @Employee
WHERE empXML.exist('ROOT/Employee[@Id=sql:variable("@EmployeeId")]') = 1 AND Id=4
Result will be as expected i.e.it will find only those rows from table where Employee Id=101 exists AND Id=4
Id
|
empXML
|
4
|
<ROOT><Employee
Id="111" /><Employee Id="107" /><Employee
Id="101" /></ROOT>
|
Now over to you:
A blog is nothing without reader's feedback and comments. So please provide your valuable feedback so that i can make this blog better and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linkedin and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates.
If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..