Skip to content
Advertisement

How to select the immediate characters BEFORE a specific string in SQL

So imagine I have a SQL tempTable with a text field with 2 pages worth of text in it.

select * from tempTable
pkid text
0 This is an example text with some images names like image1.svg or another one like image2.svg
1 This is another example text image3.svg and several images more like image4 and image5

What I want to know is if it’s possible to select the characters before the .svg extension, so that the select result would look like

result
ike image1.svg
ike image2.svg
ext image3.svg

and so on. I’ve alread read about CHARINDEX and SUBSTRING, but I’ve only been able to find selects that return ALL text before my filter (.svg).

Advertisement

Answer

So I found a way to do it. This is the query I used using PATINDEX().

select pkid, SUBSTRING (text, PATINDEX('%.svg%',text)-60,65) 
from tempTable 
where text like '%.svg%'

This way you can either return ALL text before desired word/expression, or get a certain number of characters before, you just need to change the substring ranges.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement