SELECT values from XML column from SQL server specifying WHERE clause -


i have sql table similar this:

create table #temp_xml ( id int not null, name varchar(10) null, step xml null ) truncate table #temp_xml insert #temp_xml (id, name, step) values (1, 'query 1', '<loaddata>   <step>     <stepname>step 1</stepname>     <steptype>validation</steptype>     <result>past</result>   </step>   <step>     <stepname>step 2</stepname>     <command>select cola, colb mytbl</command>     <id>888</id>   </step>   <step>     <stepname>step 3</stepname>     <command>truncate table tblabc</command>     <id>103</id>    </step>  </loaddata>')    insert #temp_xml (id, name, step) values (2, 'query 2', '<loaddata>   <step>     <stepname>step 1</stepname>     <steptype>validation</steptype>     <result>true</result>     <id>112</id>   </step>   <step>     <stepname>step 2</stepname>     <command>select cola, colb mytbl</command>   </step>   <step>     <stepname>step 3</stepname>     <command>exec dbo.mystoredproc</command>    </step>  </loaddata>')  insert #temp_xml (id, name, step) values (3, 'query 3', '<loaddata>   <step>     <stepname>step 1</stepname>     <steptype>validation</steptype>     <result>false</result>   </step>   <step>     <stepname>step 2</stepname>     <command>select cola, colb mytbl</command>     <id>666</id>   </step>   <step>     <stepname>step 3</stepname>     <command>update tblxyz set cola = ''999'' tbl_test</command>   </step>   <step>     <stepname>step 4</stepname>     <command>truncate table tblabc</command>     <id>678</id>    </step>  </loaddata>') 

i need search column step #temp_xml row has id = 678. following query not return data since there more 1 nodes.

  select * #temp_xml  step.value('(/loaddata/step/id)[1]', 'varchar(max)') = 678  

however, since 2nd time id appears, desired results:

 select * #temp_xml  step.value('(/loaddata/step/id)[2]', 'varchar(max)') = 678  

my question is, how can make search more generic, not have put occurence in square brackets [ ]?

you can use .exist(...) function xpath query.

select *  #temp_xml step.exist('/loaddata/step[id="678"]') = 1 

... if need pass in variable query can ...

declare @id int = 678;     select * #temp_xml step.exist('/loaddata/step[id=sql:variable("@id")]') = 1; 

Comments

Popular posts from this blog

PHP and MySQL WP -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

go - golang pprof for c library code -