How do you return every other character from a string from a specific starting position?
Example: starting at position 1
1050231
Result:
1521
Starting at position 2
1050231
Result:
003
How do you return every other character from a string from a specific starting position?
Example: starting at position 1
1050231
Result:
1521
Starting at position 2
1050231
Result:
003
Using a numbers table is usually the best way to avoid loops in SQL. If you don't already have a numbers table, you should go read Jeff Moden's The "Numbers" or "Tally" Table: What it is and how it replaces a loop.
To create a numbers table, you can use the following script:
SELECT TOP 10000 IDENTITY(int,1,1) AS Number
INTO Numbers
FROM sys.objects s1
CROSS JOIN sys.objects s2
ALTER TABLE Numbers ADD CONSTRAINT PK_Numbers PRIMARY KEY CLUSTERED (Number)
Now that you have a numbers table, you can use it to select the specific chars from your string like this:
DECLARE @s varchar(20) = '1050231',
@Start int = 1
SELECT Substring(@s, Number, 1)
FROM Numbers
WHERE Number >= @Start
AND (Number - @Start) % 2 = 0
AND Number <= DATALENGTH(@s)
One method uses a recursive CTE:
with cte as (
select @pos as pos, @str as str
union all
select pos + 2, str
from cte
where pos + 2 <= len(@str)
)
select substring(str, pos, 1)
from cte;
Here is a rextester.
Late answer, but here's yet another option
Example
Declare @S varchar(max) = '1050231'
Declare @P int =1
Select NewValue = (Select substring(substring(@S,@P,len(@S)),N,1)
From (Select Top (len(@S)-@P+1) N=Row_Number() Over (Order By (Select NULL)) From master..spt_values n1) A
Where N%2=1
For XML Path('')
)
Returns
NewValue
1521
The ugly way--a while loop, since Gordon gave the recursive CTE approach.
declare @string varchar(64) = 1050231
declare @start int = 1
declare @result varchar(64) = ''
set @result = @result + substring(@string,@start,1)
while @start < len(@string)
begin
set @start = @start + 2
select @result = @result + substring(@string,@start,1)
end
select @result
You could use STUFF
:
declare @i VARCHAR(20) = '1050231';
select @i = IIF(LEN(@i) >= sub.s, STUFF(@i,sub.s,1,''),@i)
FROM(SELECT 1 s UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) sub;
-- any tally table
SELECT @i;
-- 003
declare @i VARCHAR(20) = '1050231';
select @i = IIF(LEN(@i) > sub.s, STUFF(@i,sub.s+1,1,''),@i)
FROM(SELECT 1 s UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5) sub;
SELECT @i;
-- 1521