How trim() works in SQL Server - sql

I have a column SysTraNo with some specific data like
HO/20-21/DRP/0001
215/21-22/AGP/0003
I want to trim that whole column and only take 20-21 or 21-22 of that data. How can I do this?

Using the base string functions we can try:
SELECT val,
SUBSTRING(val,
CHARINDEX('/', val) + 1,
CHARINDEX('/', val, CHARINDEX('/', val) + 1) -
CHARINDEX('/', val) - 1) AS nums
FROM yourTable;
Demo
The logic here is to take a substring starting from the character after the first / until the character before the second /. On other databases, we could have used regular expressions, but SQL Server has no native support for this.

In sql server trim works like below.
As one example is above Here I have given another example using substring on email to extract the domain part.
SELECT
email,
SUBSTRING(
email,
CHARINDEX('#', email)+1,
LEN(email)-CHARINDEX('#', email)
) domain
FROM
practice
ORDER BY
email;

Related

SQL Select everything to the left of a character

I need to select everything to the left of a hyphen in a string, but some strings have 2 hyphens, in which case I need to select everything to the left of the second hyphen.
The strings are never the same length and some strings don't have hyphens at all.
Example data:
Manager-News Delivery
Co-Host-Television
Expected results:
Manager
Co-Host
How about just removing everything from the last hyphen onward?
You can do that with stuff():
select stuff(str, len(str) - charindex('-', reverse(str)) + 1, len(str), '')
from (values ('Co-Host-Television'), ('Manager-News Delivery')) v(str);
Or better yet, with left():
select left(str, len(str) - charindex('-', reverse(str)) )
from (values ('Co-Host-Television'), ('Manager-News Delivery')) v(str);
SQL isn't really meant for string manipulation, you should do that type of work in another language (on the client side? maybe).
But, it you really, really want to, and the data is small and not something you'll need to do a lot, you can use the following code:
select rtrim(reverse(substring(reverse('Manager-News Delivery'),
charindex('-',reverse('Manager-News Delivery'))+1,99)))
select rtrim(reverse(substring(reverse('Co-Host-Television'),
charindex('-',reverse('Co-Host-Television'))+1,99)))

TSQL extract part of string with regex

i would make a script that iterate over the records of a table with a cursor
and extract from a column value formatted like that "yyy://xx/bb/147011"
only the final number 147011and to put this value in a variable.
It's possible to do something like that?
Many thanks.
You don't need a cursor for this. You can just use a query. The following gets everything after the last /:
select right(str, charindex('/', reverse(str)) - 1 )
from (values ('yyy://xx/bb/147011')) v(str)
It does not specifically check if it is a number, but that can be added as well.
You can also use the below query.
SELECT RIGHT(RTRIM('yyy://xx/bb/147011'),
CHARINDEX('/', REVERSE('/' + RTRIM('yyy://xx/bb/147011'))) - 1) AS LastWord
If numeric value has exact position defined with sample data, then you can do :
SELECT t.*, SUBSTRING(t.col, PATINDEX('%[0-9]%', t.col), LEN(t.col))
FROM table t;

SQL Server - Splitting a string

I have the below string which is currently in one column, called Column1, in a table called dbo.faresnumb
Column1
512.65USD/52.65USD/0167025354825
I want to create three new columns from this string called Fare1, Fare2, Number1 like below
Fare1 Fare2 Number1
512.65USD 52.65USD 0167025354825
So the delimter is the / and the character count will not always be the exact same. For example, Fare1 could be 54.00USD rather than 512.65USD and I still need to capture everything before the first /. I know is SAS there is a way to scan a substring to find a delimiter and assign new variables, but I am new to SQL. Any help would be much appreciated!
Thanks,
Bennett
Such string operations are a pain in SQL Server. You can do:
select parts.part1 as fare1,
left(rest, charindex('/', rest) - 1) as fare2,
stuff(rest, 1, charindex('/', rest), '') as number1
from t cross apply
(values (left(col, charindex('/', col) - 1),
stuff(col, 1, charindex('/', col), '')
)
) parts(part1, rest);
Here is a rextester.
Sadly, SQL Server 2016 offers split_string() which makes this simpler. The sad part is that it does not return the position of the substring in the string. That is needed to ensure that the three extracted values are in the right order.
One more way to achieve the same using a bit of XML -
select cast(concat('<x>', REPLACE(Column1, '/', '</x><x>'), '</x>') as xml).value('/x[1]','varchar(100)'),
cast(concat('<x>', REPLACE(Column1, '/', '</x><x>'), '</x>') as xml).value('/x[2]','varchar(100)'),
cast(concat('<x>', REPLACE(Column1, '/', '</x><x>'), '</x>') as xml).value('/x[3]','varchar(100)') from dbo.faresnumb

Removing Special character from string sql

my table have column contain data like this.
SQL 2008
97W
125/ 122Q
121/ 118Q
121/ 118S
123/ 120S
112H
111H
i am trying to remove data before / so output will look like as
97W
122Q
118Q
118S
120S
112H
111H
can anyone share experience how can i achieve if came across such scenario.
Thanks,
Try this:
SELECT LTRIM(RIGHT(mycol, LEN(mycol) - CHARINDEX('/', mycol)))
FROM mytable
Demo here
Look at this one
Select LTRIM(SUBSTRING(col, CHARINDEX('/', col) + 1, LEN(col)))
from table
Use a CASE expression to check whether the string contains /, if yes use CHARINDEX to find the index of / and get the right part. Else the string as it is.
Query
SELECT
CASE WHEN your_column_name LIKE '%/%'
THEN LTRIM(RIGHT(your_column_name, CHARINDEX('/', REVERSE(your_column_name), 1) - 1))
ELSE your_column_name END AS new_string
FROM your_table_name;
SQL Fiddle Demo

How to get a id from a url using SQL QUERY. The ID changes dynamically. the database is Sql server 2008

I have url like:
http://mysites.xyz.com/_layouts/ng/ActivityStream.aspx/id/2624D92223261D370D7287C9E83CAEEA/Activity%20Stream%20Post.
I need to get the 2624D92223261D370D7287C9E83CAEEA. But not able to do so. my current query is
SUBSTRING(#URL2,LEN('http://mysites.xyz.com/_layouts/ng/ActivityStream.aspx/id/'),LEN(#URL2)-LEN('http://mysites.xyz.com/_layouts/ng/ActivityStream.aspx/id/')- CHARINDEX('/',REVERSE(#URL2))))
Please suggest.
Try this:
SELECT SUBSTRING(
#URL2,
CHARINDEX('/id/', #URL2)+4,
CHARINDEX('/', #URL2, CHARINDEX('/id/', #URL2)+5)
- (CHARINDEX('/id/', #URL2)+4))
Note: This assumes that the id is always followed by at least one more slash.
Breakdown:
The first argument of the substring is the string that contains the full expression.
The second one is the first index after /id/.
The third one is the desired length - calculated by the first index of / after /id/ - the first index after /id/.
update
To cope with strings that does not contain a slash after the id value, use case:
SELECT SUBSTRING(
#URL,
CHARINDEX('/id/', #URL)+4,
CASE WHEN CHARINDEX('/', #URL, CHARINDEX('/id/', #URL)+5) > 0 THEN
CHARINDEX('/', #URL, CHARINDEX('/id/', #URL)+5)
- (CHARINDEX('/id/', #URL)+4)
ELSE
LEN(#URL)
END
)
If the structure is always the same then you can try:
SELECT REPLACE(RIGHT(#s, LEN(#s) - 58), '/Activity%20Stream%20Post', '')
or:
SELECT REPLACE(REPLACE(#s,'/Activity%20Stream%20Post', ''), 'http://mysites.xyz.com/_layouts/ng/ActivityStream.aspx/id/', '')