Substring from position to position in SQL server

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).





length = pos2-pos1, doesn't it?
– Ivan Starostin
Aug 30 at 9:20





There is no "EXTRACT" function with the parameters Start Position and End Position. SUBSTRING, operates with Start Position and Number of Characters, just like most programming languages (I say most, as I'm sure there's an exception, I just don't know one). If you want a function like that, you'd have to write one (but why, I don't know, when SUBSTRING already serves the exact same purpose and the second parameter can easily be derived).
– Larnu
Aug 30 at 9:48



EXTRACT


Start Position


End Position


SUBSTRING


Start Position


Number of Characters


SUBSTRING




2 Answers
2



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)





Thanks for that. I was actually looking for another function that I might not be familiar with ... But that should work for sure.
– IZ4
Aug 30 at 9:29



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


@pos


@endpos


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



This eliminates the calculation of the length.



Required, but never shown



Required, but never shown






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế