Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2005 - how can I select a specific part of a string?

I have the string &string=45646874&v1=67&v2=test and from that I would like to grab the string 45646874 and sometime this extraction will have 8 characters sometimes 7 sometimes 5 etc.

So I need to search in &string=45646874&v1=67&v2=test and grab everything that comes after string= and before the next &

like image 875
Felipe Jordani Avatar asked Dec 20 '25 22:12

Felipe Jordani


1 Answers

SQL Server does not have any built in regex extraction support, but we can handle this using the base string functions as follows:

WITH cte AS (
    SELECT '&string=45646874&v1=67&v2=test' AS col UNION ALL
    SELECT 'blah blah &string=ABCDEF123&v1=hello&v2=goodbye'
)

SELECT
    SUBSTRING(col, CHARINDEX('&string=', col) + 8,
              CHARINDEX('&', col, CHARINDEX('&string=', col) + 1) -
              CHARINDEX('&string=', col) - 8) AS output
FROM cte;

enter image description here

Demo

like image 75
Tim Biegeleisen Avatar answered Dec 22 '25 15:12

Tim Biegeleisen



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!