Reputation:
I want to extract a certain phrase from a column after a/any symbol. For example, If I want to extract Tutorial from SQL-Tutorial, following query shall suffice.
SELECT SUBSTRING('SQL-Tutorial', 5, 8) AS ExtractString;
What if I want to extract everything before or after '-' or '_' from the following fields in a column?
Upvotes: 1
Views: 3458
Reputation: 5893
CREATE TABLE #Table1
([COLN] varchar(24))
;
INSERT INTO #Table1
([COLN])
VALUES
('SQL-Tutorial'),
('Oracle-Tutorial'),
('IBM DB2-Tutorial'),
('Sybase ASE-Tutorial'),
('PostgreSQL-Tutorial'),
('MariaDB-Tutorial'),
('MySQL-Tutorial'),
('Teradata-Tutorial'),
('IBM Informix-Tutorial'),
('Amazon SimpleDB-Tutorial')
;
SELECT PARSENAME(REPLACE(coln,'-','.'),2) [before],
PARSENAME(REPLACE(coln,'-','.'),1) [after] from #Table1
output
before after
SQL Tutorial
Oracle Tutorial
IBM DB2 Tutorial
Sybase ASE Tutorial
PostgreSQL Tutorial
MariaDB Tutorial
MySQL Tutorial
Teradata Tutorial
IBM Informix Tutorial
Amazon SimpleDB Tutorial
Upvotes: 2
Reputation: 367
You Can use SUBSTRING and CHARINDEX to get before and after of any character like -
SELECT SUBSTRING(@String,0,CHARINDEX('-',@String,0)) As Before_str,
SUBSTRING(@String,CHARINDEX('-',@String)+1,LEN(@String)) As After_str
Upvotes: 1
Reputation: 1649
If you are using SQL Server the below code can extract everything before and after the char '-', the where condition is there to validate if there is a char '-' in first place to split like that
SELECT
LEFT([COLUMN],charindex('-',[COLUMN])-1) as BeforeString,
RIGHT([COLUMN],len([COLUMN])-charindex('-',[COLUMN])) as AfterString
FROM [TABLE]
WHERE charindex('-',[COLUMN])<>0
Upvotes: 1