Firstly, see the (more than valid) comment from F-ES Sitecore.
However if you really must parse this string then there are several ways to go about it.
You might think of using a loop and using
PATINDEX[
^] to find the numeric bits e.g.
PATINDEX('%[0-9]%',@String)
and/or the non-numeric bits
PATINDEX('%^[0-9]%',@String)
. I would not recommend that approach.
My preferred approach...
You could split the string into it's component parts using
STRING_SPLIT [
^] (from SQL 2016, Google for an alternative solution if you have an earlier version), so you end up with a table like this:
1 30
2 Years
3 3
4 Month
5 2
6 Weeks
7 2
8 day
Then you can do something like this
;with CTE AS
(
select ID, part, LEAD(part) OVER (ORDER BY id) AS descriptor
from @split
)
SELECT '@' + descriptor + '=' + part
FROM CTE
WHERE ID % 2 = 1
which gives you
@Years=30
@Month=3
@Weeks=2
@day=2
But that is not consistent with the descriptors so I would take it a step further and do something like
declare @descriptors table (part varchar(30), descriptor varchar(30))
insert into @descriptors (part, descriptor) values
('day','@days='),
('days','@days='),
('week','@weeks='),
('weeks','@weeks='),
('month','@month='),
('months','@months='),
('year','@years='),
('years','@years=')
;with CTE2 AS
(
select ID, part, LEAD(part) OVER (ORDER BY id) AS descrip
from @split
)
SELECT descriptor + a.part
FROM CTE2 A
INNER JOIN @descriptors B ON A.descrip = B.part
WHERE ID % 2 = 1
which gives
@years=30
@month=3
@weeks=2
@days=2
You'll then want to create a comma-separated list from those values - there are loads of
suggestions[
^] on that.
which takes me right back to F-ES Sitecore's comment ... your design is not the right way to go about this