2

I have a Database Table where i have some data in XML datatype.

Following is an example of some data in that column.

<locale en-US="Test &amp; Data" />

Is there any way to extract only the words "Test & Data" in SQL server. Is there any built in function.

MarsOne
  • 2,155
  • 5
  • 29
  • 53

3 Answers3

5

Try something like this.

If you have a XML variable:

declare @xml XML = '<locale en-US="Test &amp; Data" />';

select 
  data.node.value('@en-US', 'varchar(11)') my_column
from @xml.nodes('locale') data(node);

In your case, for a table's column (sorry for not given this example first):

create table dbo.example_xml
(
    my_column XML not null
);
go

insert into dbo.example_xml
values('<locale en-US="Test &amp; Data" />');
go

select
  my_column.value('(/locale/@en-US)[1]', 'varchar(11)') [en-US]
from dbo.example_xml;
go

Hope it helps.

Luis de Haro
  • 711
  • 1
  • 7
  • 28
1
IF OBJECT_ID('tempdb..#Holder') IS NOT NULL
begin
    drop table #Holder
end


CREATE TABLE #Holder
(ID INT , MyXml xml )


/* simulate your insert */
INSERT INTO #HOLDER (ID , MyXml) 
select 1 , '<locale en-US="Test &amp; Data" />' 
union all select 2 , '<locale en-US="Barney &amp; Friends" />'

/* with other values in the table */

SELECT
    holderAlias.ID , 
    pre.value('(@en-US)[1]', 'Varchar(50)') AS 'ItemID'
FROM
    #Holder holderAlias CROSS APPLY
      MyXml.nodes('/locale') AS MyAlias(pre)

/* OR */

SELECT
    [MyShreddedValue] = holderAlias.MyXml.value('(/locale/@en-US)[1]', 'varchar(50)')
FROM
    #Holder holderAlias


IF OBJECT_ID('tempdb..#Holder') IS NOT NULL
begin
    drop table #Holder
end
granadaCoder
  • 26,328
  • 10
  • 113
  • 146
1

Please take a look in this example called: How to read XML column in SQL Server 2008? (here in stack overflow)

This is a very simple example:

SELECT 
Configuracion.value('(/YourTag/Values)[1]', 'VARCHAR(255)')as columnName, 
FROM yourTable
Community
  • 1
  • 1
Orlando Herrera
  • 3,481
  • 1
  • 34
  • 44