Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL return every other character from string

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
like image 997
Bobby Zimmerman Avatar asked Apr 23 '26 16:04

Bobby Zimmerman


1 Answers

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)
like image 93
Zohar Peled Avatar answered Apr 25 '26 14:04

Zohar Peled



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!