I am trying to create a while loop in SQL and it seems kind of complex. Here's what I need it to achieve:
- Iterate through a single VARCHAR string (ex. '123')
- If the nth character is in an even position in the string (ex. 2nd, 4th .... letter in the string), it must be added(SUM) to a base variable (Let's assume @z)
- If the nth character is in an odd position in the string (ex. 1st, 3rd .... letter in the string), it must be multiplied by 2. If this newly generated value (Let's assume @y) is less than 10, it must be added(SUM) to the base variable (Still the same assumed @z). If @y is greater than 10, we need to subtract 9 from @y before adding(SUM) it to @z
After iterating through the entire string, this should return a numeric value generated by the above process.
Here is what I've done so far, but I'm stuck now (Needless to say, this code does not work yet, but I think I'm heading in the right direction):
DECLARE @x varchar(20) = '12345'
DECLARE @p int = len(@x)
WHILE @p > 0
SELECT @x =
stuff(@x, @p, 1,
case when CONVERT(INT,substring(@x, @p, 1)) % 2 = 0 then CONVERT(INT, @x) + CONVERT(INT,substring(@x, @p, 1))
end), @p -= 1
RETURN @x;
PS. The input will always be 100% numeric values, but it is formatted as VARCHAR when I recieve it.
UPDATE
The expected result for the sample string is 15