Question

I have a table with 2 columns first is an integer column with primary keys and the second is a xml column with data.

The data column contains the xml as follows

<Fields>
    <Field1>10</Field1>
    <Field2>11</Field2>
    <Field3>10</Field3>
    <Field4>11</Field4>
</Fields>

The number of fields are not fixed and may vary in each row. I want to write a stored procedure which accepts 2 parameters the comma separated primary keys and comma separated string. So my 2 parameters will be

32,54,63,653
Field1,Field2

The sp will return a datatable with the following

32 | <Fields><Field1>10</Field1><Field2>11</Field2></Fields>
54 | <Fields><Field1>50</Field1><Field2>62</Field2></Fields>
63 | <Fields><Field1>32</Field1><Field2>542</Field2></Fields>
653| <Fields><Field1>15</Field1><Field2>21</Field2></Fields>

I am facing problems in selecting only the required nodes from the xmls in the data column.

Edit

I have tried the following

select PricingXML.query('/Fields/Field1') from T_SMPricingData 

But I want the above for many fields not only the field1

Était-ce utile?

La solution

Use a split string function of your choice something like this.

create function dbo.SplitString
(
  @List nvarchar(max),
  @Delimiter nvarchar(255)
)
returns table
with schemabinding
as
return 
(  
  select Item = T2.X.value('text()[1]', 'nvarchar(4000)')
  from (
       select convert(xml, N'<N>' + replace((select @List for xml path('')), @delimiter, N'</N><N>') + N'</N>').query('.')
       ) as T1(X)
    cross apply T1.X.nodes('N') as T2(X)
);

Use that in a stored procedure like this.

create procedure GetPricing
  @IDs nvarchar(max),
  @Nodes nvarchar(max)

as
select T.ID,
       (
       select F.X.query('.')
       from T.PricingXML.nodes('/Fields/*') as F(X)
         inner join dbo.SplitString(@Nodes, ',') as N
           on F.X.value('local-name(.)', 'nvarchar(100)') = N.Item
       for xml path(''), root('Fields'), type
       ) as PricingXML
from dbo.T_SMPricingData as T
  inner join dbo.SplitString(@IDs, ',') as N
    on T.ID = cast(N.Item as int)

SQL Fiddle

Autres conseils

Try this:

select
  Roles
from
  MyTable
where
  Roles.value('(/root/role)[1]', 'varchar(max)') like 'StringToSearchFor'

you may find more sample code here and here.

Also, you may be interested in this fiddle that shows how to look in xml columns.

I'm used to see XML in the following way:

<School>
  <Class>Geography</Class>
  <Class>Mathematics</Class>
  <Class>Programming</Class>
  <teacher>Mrs Crabaple</Teacher>
</School>

field1, field2 are pretty meaningless. Give them meanings.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top