Search code examples
databasestringsubstringbracketscharindex

How to find only last part of string with brackets using MS SQL


I have a long string with multiple bracket inside string , i am tried to fetch only last part of the string , But i have achieved first part till end.

 Alkyl acrylate-Styrene (or alpha-Methylstyrene) copolymer (Substances not 
 requiring notification is limited to the following: Copolymer of butyl 
 acrylate / styrene (It is limited that the polymer is insoluble in water, acid 
 and alkali, and the content of the components having molecular weight less 
 than 1,000 is 1% or less.))

My Query :

SELECT  [RigNumSrc],[SubSRC],
case when  CHARINDEX(' (',[SubSRC])<>0  then LEFT ([SubSRC], charindex (' (', 
[SubSRC])-1)  
         when  CHARINDEX(' (',[SubSRC])=0 then [SubSRC] end as [chemnamesrc1]
 ,case when  CHARINDEX(' (',[SubSRC])<>0  then SUBSTRING([SubSRC], 
CHARINDEX(' 
(',[SubSRC]),LEN([SubSRC]))
end as synamesrc1 from xyztable

my result :

    (or alpha-Methylstyrene) copolymer (Substances not requiring notification 
    is limited to the following: Copolymer of butyl acrylate / styrene (It is 
    limited that the polymer is insoluble in water, acid and alkali, and the 
    content of the components having molecular weight less than 1,000 is 1% 
     or less.))

Please help me to find only :

 (It is limited that the polymer is insoluble in water, acid 
 and alkali, and the content of the components having molecular weight less 
 than 1,000 is 1% or less.)

Solution

  • TRY :

    DECLARE @myString VARCHAR(MAX)='Alkyl acrylate-Styrene (or alpha-Methylstyrene) copolymer (Substances not requiring notification is limited to the following: Copolymer of butyl 
    acrylate ( styrene (It is limited that the polymer is insoluble in water, acid and alkali, and the content of the components having molecular weight less than 1,000 is 1% or less.))'
    
    SELECT CASE WHEN RIGHT(@myString,1) <> ')' THEN NULL ELSE REPLACE(RIGHT(@myString , CHARINDEX ('(' ,REVERSE(@myString))),'))',')') END