简体   繁体   中英

Extracting a part of String in SQL Server

I have a field that returns a string value in this format xxxxxxx(xxxxx) . Now I need to extract the content of the string inside () as well the ones before (). How can I achieve this?

Please try:

declare @var nvarchar(100)='xxxxxxx(xxxxx)'

select @var, 
    LEFT(@var, charindex('(', @var, 1)-1), 
    replace(right(@var, charindex('(', @var, 1)-1), ')', '')
declare @str varchar(100)

set @str='xxxxx(aaa)'

---- extracts xxxxx
select SUBSTRING(@str,0,CHARINDEX('(',@str)) 

---- extracts aaa
select SUBSTRING(@str,CHARINDEX('(',@str)+1,CHARINDEX(')',@str)-CHARINDEX('(',@str)-1)

` Dont have much idea about sql server.

bt in oracle you can achieve this as follow:

SELECT SUBSTR('xxxxxxx(xxxxx)',0,instr('xxxxxxx(xxxxx)','(')-1)            AS first_part,
SUBSTR('xxxxxxx(xxxxx)',instr('xxxxxxx(xxxxx)','(')+1,instr('xxxxxxx(xxxxx)',')')-instr('xxxxxxx(xxxxx)','(')-1) AS second_part
FROM dual;

so try to find the respective syntax. substr is self explanatory. and instr returns the position of 1st occurrence of a character in a given string.

TEchDo answer is perfect, he just missed out one other replace function for the second column.

declare @var nvarchar(100)='xxxxxxx(xxxxx)'  

select @var AS Source, LEFT(@var, charindex('(', @var, 1)-1) AS FirstColumn,   
replace(replace(right(@var, charindex('(', @var, 1)-1), ')',''),'(','') AS SecondColumn

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM