ZedZip
ZedZip

Reputation: 6488

SQL XML query from column

How to select file names from this kind of XML in a SQL Server column?

  1. file name is in attribute VALUE only if high level tag is object with name File like this

    <Object NAME="File">
        <Parameter ID="1" NAME="Name" VALUE="\\mysvr\fiels\readme1.txt" />
    </Object>
    
  2. This sub-hierarchy can be placed on any level of xml (see example below)

  3. XML column can contain 0-N file names, I need list like this:

    id, filename
    --- ------------------------
     1  \\mysvr\fiels\readme1.txt
     1  \\mysvr\fiels\readme2.txt
     2  \\mysvr\fiels\readme3.txt
     2  \\mysvr\fiels\readme4.txt
    

Example of XML contents:

declare @t1 table
(   id int,
   x XML
)

insert into @t1 (id, x)
select 1,N'<root name="name" id="12">
<class1>
  <Object NAME="File">
              <Parameter ID="1" NAME="Name" VALUE="\\mysvr\fiels\readme1.txt" />
   </Object>
</class1>
<class1>
<subclass1>
<Object NAME="File">
              <Parameter ID="10" NAME="Name" VALUE="\\mysvr\fiels\readme2.txt" />
</Object>
<Object NAME="bitmap">
              <Parameter ID="11" NAME="my1" VALUE="bmp" />
</Object>
</subclass1>
</class1>
</root>'
union 
select 2,N'<root name="name" id="12">
<class1>
  <Object NAME="File">
              <Parameter ID="13" NAME="Name" VALUE="\\mysvr\fiels\readme3.txt" />
  </Object>
  <Object NAME="Font">
              <Parameter ID="22" NAME="Tahoma" VALUE="11" />
  </Object>
</class1>
<class1>
<subclass1>
  <Object NAME="File">
              <Parameter ID="14" NAME="Name" VALUE="\\mysvr\fiels\readme4.txt" />
  </Object>
</subclass1>
</class1>
</root>'

Upvotes: 1

Views: 224

Answers (2)

marc_s
marc_s

Reputation: 755321

Try this:

SELECT
    id,
    Filename = ObjPrm.value('@VALUE', 'varchar(100)')
FROM @t1
CROSS APPLY x.nodes('//Object[@NAME="File"]/Parameter') AS Tbl(ObjPrm)

Gives me an output of:

enter image description here

Upvotes: 1

Ruan
Ruan

Reputation: 4293

To do this you can do the following.

Define a string of the specific details you want to display.

You want to display id and Name so your string will look something like this.

String holder = "#id# -- #VALUE#"

Then you search through that whole string for the values you have between the two '#' signs.

When you find them, just do a search for the value inside the Quotation marks, and display them.

Upvotes: 0

Related Questions