Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Function to remove text in brackets

Author  Topic 

grimmus
Yak Posting Veteran

53 Posts

Posted - 2008-03-03 : 13:14:28
Hi,

I am looking for a function that can remove the brackets and text within them in a given string.

i.e. 'Hello World (text in brackets)' becomes just 'Hello World'

Thanks alot

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2008-03-03 : 14:13:46
Here is one way:
DECLARE @Yak TABLE (Val VARCHAR(100))

INSERT @Yak
SELECT 'Hello World (text in brackets)'
UNION ALL SELECT 'Hello World )text in brackets)'
UNION ALL SELECT 'Hello World (text in brackets('
UNION ALL SELECT 'Hello World text in brackets'
UNION ALL SELECT '(text in brackets)Hello World'
UNION ALL SELECT 'Hello (text in brackets) World'

SELECT
CASE
WHEN CHARINDEX('(', Val) > 0 AND CHARINDEX(')', Val) > 0 AND CHARINDEX('(', Val) < CHARINDEX(')', Val)
THEN STUFF(Val, CHARINDEX('(', Val), (CHARINDEX(')', Val) - CHARINDEX('(', Val)) + 1, '')
ELSE Val
END
FROM
@Yak
Go to Top of Page
   

- Advertisement -