0

I have almost no experience with querying XML data with T-SQL. Given the XML shown below, how would I extract the 'Sub_ID' value?

<MESSAGE LABEL = "IVSWEEP" >
    <H 
        SIMULATOR = "54355" 
        COMMENT = "" 
        OPERATOR = "Operator" 
        SUB_ID = "090617041199" 
        PROCESS_CD = "AHIPOT" 
        DATE_TIME = "6/19/2009 11:57:35 AM" 
        TMOD = "23.05" 
        TCOR = "23.05" 
        <D P = "0" I = "0" V = "0" />
        <D P = "1" I = "1.250854" V = "0" />
        <D P = "2" I = "1.251904" V = "4.212341" />
        <D P = "3" I = "1.24895" V = "7.517395" />
    </H>
</MESSAGE>
2
  • Could you use Linq to XML instead? Here's one short example: hookedonlinq.com/LINQtoXML5MinuteOverview.ashx Commented Feb 22, 2011 at 16:27
  • @DOK - I wish, but not in this case. I already know how to do this in L2XML. I need to parse this from a stored proc. Commented Feb 22, 2011 at 16:28

1 Answer 1

1

Here is one way. Your XML was invalid. Missing a > to terminate <H.

declare @xml xml = '<MESSAGE LABEL = "IVSWEEP" >
    <H 
        SIMULATOR = "54355" 
        COMMENT = "" 
        OPERATOR = "Operator" 
        SUB_ID = "090617041199" 
        PROCESS_CD = "AHIPOT" 
        DATE_TIME = "6/19/2009 11:57:35 AM" 
        TMOD = "23.05" 
        TCOR = "23.05"> 
        <D P = "0" I = "0" V = "0" />
        <D P = "1" I = "1.250854" V = "0" />
        <D P = "2" I = "1.251904" V = "4.212341" />
        <D P = "3" I = "1.24895" V = "7.517395" />
    </H>
</MESSAGE>'

declare @T table (Col1 xml)
insert into @T values(@xml)
insert into @T values(@xml)
insert into @T values(@xml)

select 
  m.h.value('@SUB_ID', 'varchar(50)')
from @T
  cross apply Col1.nodes('MESSAGE/H') as m(h)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. I forgot to mention one thing. I am reading the XML values from rows in a table. How would I do this if I had to process many rows at a time, and retrieve the SUB_ID value from each row?
@Randy: Updated answer with a table version.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.