IZ4
IZ4

Reputation: 23

Substring from position to position in SQL server

Is there an easy way to extract a string from a defined position to another defined position? (unlike the Substring Function where the last parameter is the length of the string being extracted).

Upvotes: 0

Views: 4081

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269633

If you have @pos and @endpos, you might find this useful:

select stuff(stuff(@str, @endpos + 1, len(@str), ''), 1, @pos - 1, '')

This eliminates the calculation of the length.

Upvotes: 1

MJH
MJH

Reputation: 1750

Yep, basic maths:

declare @v varchar(200),
        @p1 int,
        @p2 int

select  @v = 'One Two Three',
        @p1 = 5,
        @p2 = 7

select  substring(@v, @p1, (@p2-@p1)+1)

Upvotes: 2

Related Questions