-1

Can some one kindly suggest ways by which I can extract 0459 and 0460 from a string like (&0459&/&0460&)*100 in a SQL Server table?

I should be able to pull out two strings sandwiched between two pair of ampersands.

Thanks in advance.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
VivekDev
  • 20,868
  • 27
  • 132
  • 202

2 Answers2

1

If you are certain there are always two pair of ampersands you may extract the two strings like this

declare @s varchar(max) = '(&0459&/&0460&)*100'

declare @first int = charindex('&', @s)
declare @second int = charindex('&', @s, @first+1)
declare @third int = charindex('&', @s, @second+1)
declare @fourth int = charindex('&', @s, @third+1)

select substring(@s, @first+1, @second-@first-1)
select substring(@s, @third+1, @fourth-@third-1)
Svein Fidjestøl
  • 3,106
  • 2
  • 24
  • 40
1

This solution will grap 1st and 3th value between '&'

;WITH CTE AS
(
     SELECT t.c.value('.', 'VARCHAR(2000)') v,
     rn = row_number() over (order by (select 1))-1
     FROM (
         SELECT x = CAST('<t>' + 
               REPLACE('(&0459&/&0460&)*100', '&', '</t><t>') + '</t>' AS XML)
     ) a
     CROSS APPLY x.nodes('/t') t(c)
)
SELECT v FROM CTE
WHERE rn in (1,3)

Result:

0459
0460
t-clausen.dk
  • 43,517
  • 12
  • 59
  • 92