Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server split string and access different parts of it

Tags:

sql

sql-server

I need to update the url stored in a column.

My columns have values like this:

https://www.site.sharepoint.com/sites/test/AB-19-CALL

I want to update this URL to:

https://www.site.sharepoint.com/sites/test/CALL-AB-19

To get the last part which is AB-19-CALL, I used the below query

SELECT 
    SUBSTRING(urlcompte, LEN(urlcompte) - CHARINDEX('/', REVERSE(urlcompte)) + 2, LEN(urlcompte)), 
    UrlCompte 
FROM 
    tblAccount

Now to split and reverse the AB-19-call I would again need to use the entire query above and then select substring using -

Is there an easier way to do this?

In C# we can do something like this:

urlCompte.Split('-')[2] + urlCompte.Split('-')[0] + urlCompte.Split('-')[1] 

Is there a way in SQL Server to split the column and access different parts of it?

like image 788
Vignesh Subramanian Avatar asked Jan 27 '26 15:01

Vignesh Subramanian


1 Answers

This would work to split the string parts -

DECLARE @txt NVARCHAR(500)= 'https://www.site.sharepoint.com/sites/test/AB-19-CALL';

SELECT value
FROM STRING_SPLIT(REVERSE(SUBSTRING(REVERSE(@txt), 1, CHARINDEX('/', REVERSE(@txt))-1)), '-');(substring(reverse(@txt),1,charindex('/',reverse(@txt))-1)),'-')
like image 96
jptr Avatar answered Jan 29 '26 05:01

jptr



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!