How to use substring and PatIndex in SQL Server - sql

How to substring data. For example, I have data like this:
+----------------------+
|John123123412412wqeqw |
|May1231243334234wawdd |
|Jo02930124010284jahdj |
|dy827837127912938hygb |
+--------------------- +
I want the output to be like this:
+----------------------+
|John |
|May |
|Jo |
|dy |
+--------------------- +
As of now I don't understand how to Apply Substring and charindex in my script.
Thanks in advance!

You can try LEFT and PATINDEX with a pattern to match the numbers like PATINDEX('%[0-9]%', 'John123123412412wqeqw').
Sample code
DECLARE #Text VARCHAR(500);
SET #Text = 'John123123412412wqeqw';
SELECT LTRIM(RTRIM(LEFT(#Text, PATINDEX('%[0-9]%', #Text) - 1)))
You can do this from the table as below
SELECT
LTRIM(RTRIM(LEFT(ColumnName, PATINDEX('%[0-9]%', ColumnName) - 1)))
FROM
[Table1]

Best way to handle the strings and there manipulation is in application side and not in database side. But if you required this then you can use PATINDEX along with SUBSTRING to get what you want,
SELECT PATINDEX('%[^0-9]%',stringValueCol) 'Position of NonNumeric String Position',
SUBSTRING(stringValueCol,PATINDEX('%[^0-9]%',stringVlaueCol),PATINDEX('%[^A-Z]%',stringValueCol)-1) 'NonNumeric String'
FROM
myTable
But I would still suggest do this manipulations in code and not on database side.

Related

SQL - trimming values before bracket

I have a column of values where some values contain brackets with text which I would like to remove. This is an example of what I have and what I want:
CREATE TABLE test
(column_i_have varchar(50),
column_i_want varchar(50))
INSERT INTO test (column_i_have, column_i_want)
VALUES ('hospital (PWD)', 'hopistal'),
('nursing (LLC)','nursing'),
('longterm (AT)', 'longterm'),
('inpatient', 'inpatient')
I have only come across approaches that use the number of characters or the position to trim the string, but these values have varying lengths. One way I was thinking was something like:
TRIM('(*',col1)
Doesn't work. Is there a way to do this in postgres SQL without using the position? THANK YOU!
If all the values contain "valid" brackets, then you may use split_part function without any regular expressions:
select
test.*,
trim(split_part(column_i_have, '(', 1)) as res
from test
column_i_have | column_i_want | res
:------------- | :------------ | :--------
hospital (PWD) | hopistal | hospital
nursing (LLC) | nursing | nursing
longterm (AT) | longterm | longterm
inpatient | inpatient | inpatient
db<>fiddle here
You can replace partial patterns using regular expressions. For example:
select *, regexp_replace(v, '\([^\)]*\)', '', 'g') as r
from (
select '''hospital (PWD)'', ''nursing (LLC)'', ''longterm (AT)'', ''inpatient''' as v
) x
Result:
r
-------------------------------------------------
'hospital ', 'nursing ', 'longterm ', 'inpatient'
See example at db<>fiddle.
Could it be as easy as:
SELECT SUBSTRING(column_i_have, '\w+') AS column_i_want FROM test
See demo
If not, and you still want to use SUBSTRING() to get upto but exclude paranthesis, then maybe:
SELECT SUBSTRING(column_i_have, '^(.+?)(?:\s*\(.*)?$') AS column_i_want FROM test
See demo
But if you really are looking upto the opening paranthesis, then maybe just use SPLIT_PART():
SELECT SPLIT_PART(column_i_have, ' (', 1) AS column_i_want FROM test
See demo

Select specific data after defined decimal

I have a column that contains version information in a format like:
20.6.4.4200
10.28.30.2678
22.8.34.1200
I’m wanting to only select the values after the last decimal like:
4200
2678
1200
What is the best way to do this or is a Regex needed?
In SQL Server, that has poor regex support, you can use string functions as follows:
right(val, charindex('.', reverse(val)) - 1)
The idea is to get the position of the last dot in the string, counting from the end of the string, then extract the relevant part of the string with right().
Demo on DB Fiddle:
select val, right(val, charindex('.', reverse(val)) - 1) new_val
from (values('20.6.4.4200'), ('10.28.30.2678'), ('22.8.34.1200')) t(val)
GO
val | new_val
:------------ | :------
20.6.4.4200 | 4200
10.28.30.2678 | 2678
22.8.34.1200 | 1200
A regular expression is probably the simplest method. Databases that support regular expressions usually support something that retrieves a substring. The syntax would be like:
select regexp_substr(col, '[0-9]+$')
Of course, the function might have a different name.

How to trim data with last alphanumeric key as reference

Need your help on below Data trimming or what so ever to get the result that shows also on below. I want to get the data where my reference is the last - symbol.
See example below.
FROM TO
+-------------------------------+
|ABC-1234-AR-R | ABC-1234-AR |
|ABC-1254-AR-IT | ABC-1254-AR |
|ABC-1223-AR-LTL| ABC-1223-AR |
|ABC-1234-R | ABC-1234 |
+-------------------------------+
This will give you index of last occurence of a hyphen:
LEN(data) - CHARINDEX('-', REVERSE(data)) + 1
So it's enough to take substring of this length:
SELECT
data,
SUBSTRING(data, 1, LEN(data) - CHARINDEX('-', REVERSE(data))) AS data_trimmed
FROM yourTable;
Demo
You can also use a combination of LEFT and CHARINDEX functions.
Query
select [from],
left([from], len([from]) - charindex('-', reverse([from]), 1)) as [to]
from [your_table_name];
Find a demo here

SQL View SUBSTRING and CHARINDEX

I have a query in SQL 2008
SELECT [orde_reference],
SUBSTRING([orde_reference],
CHARINDEX('/', [orde_reference]) + 1,
LEN([orde_reference])) AS batch
FROM Orders
That returns the following
orde_reference: 27777/2012/1
batch: 2012/1
However I need the batch to just be the characters after the last / (there are always 2 x '/' in the varchar
orde_reference: 27777/2012/1
batch: 1
Any help would be appreciated.
Cheers
Mim
Try
SELECT orde_reference,
RIGHT(orde_reference, CHARINDEX('/', REVERSE(orde_reference)) - 1) batch
FROM orders
Sample output:
| ORDE_REFERENCE | BATCH |
--------------------------
| 27777/2012/1 | 1 |
| 27734/2013/11 | 11 |
Here is SQLFiddle demo
As there are always 2 / you can pass the optional third argument to CHARINDEX (start_location) to tell it to start looking after the first one.
SELECT [orde_reference],
SUBSTRING([orde_reference],
CHARINDEX('/', [orde_reference],1 + CHARINDEX('/', [orde_reference])) + 1,
LEN([orde_reference])) AS batch
FROM Orders
You would be better off storing these components individually however in separate columns.
Use REVERSE twice ;)
SELECT [orde_reference]
,REVERSE(SUBSTRING(reverse([orde_reference]), 0, CHARINDEX('/', reverse([orde_reference])))) AS batch
from (values(
' 27777/2012/123'
)) as O([orde_reference])

SQL search for complex string within a row

Ok so I have a database row with a specified string in for example i am here.
I want to know how I could match this row (in a T-SQL query) if for example my input was hello i am here in this bright room.
To be clearer and get a better answer hopefully, here is a rough example:
Table:
1 | i am there |
2 | i am here |
3 | i am not here |
Problem:
I have the input hello i am here in this bright room - this should return a match to row 2 above only as only row 2 contains i am here definitively whilst the others contain the characters for i am here but with subtle differences.
If anyone can help it would be much appreciated. I would like to do this all in SQL so I can create a stored procedure for the above.
DECLARE #InputString VARCHAR(100);
SET #InputString = 'hello i am here in this bright room';
SELECT *
FROM YourTable
WHERE CHARINDEX(YourColumn, #InputString) <> 0;
declare #input as varchar
set #input = 'hello i am here in this bright room'
select *
from MyTable
where #input like '%' + MyCol + '%'