0

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?

4
  • so you need to the values as two columns? Commented Apr 29, 2014 at 7:02
  • 1
    You have a poorly designed column then. If these are actually two separate pieces of data, they ought to be stored in their own, separate, columns. If so desired, you could then have a computed column that assembles them together and adds the brackets, for display purposes. Commented Apr 29, 2014 at 7:03
  • Yes , I need them as two columns.@TechDo Commented Apr 29, 2014 at 7:04
  • Its not a poorly designed Column. Its just a client requirement that they wanted to separate certain part of a code. @Damien_The_Unbeliever Commented Apr 29, 2014 at 7:05

4 Answers 4

1

Please try:

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

select @var, 
    LEFT(@var, charindex('(', @var, 1)-1), 
    replace(right(@var, charindex('(', @var, 1)-1), ')', '')
Sign up to request clarification or add additional context in comments.

Comments

0
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)

Comments

0

` 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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.