Friday, March 23, 2012

Need SQL Help - Trim parentheses in column of data

Hi All, I am sure someone has done this before. Trying to write a SQL statement to UPDATE a column named Prod_Model. The table name is tbl_MASTER. Wanting to trim the parentheses out of the data and update back to the table. Any help on the SQL statement?

Trim or remove? Trim usually means only leading and/or trailing, and remove means to get rid of all.

Here is how to remove:

UPDATE Table

SET field=REPLACE(REPLACE(field,')',''),'(','')

WHERE field LIKE '%)%' OR field LIKE '%(%'

Here is how to trim:

UPDATE Table

SET field=REVERSE(SUBSTRING(REVERSE(SUBSTRING(field,PATINDEX('%[^()]%',field),LEN(field)-PATINDEX('%[^()]%',field)+1)),PATINDEX('%[^()]%',REVERSE(SUBSTRING(field,PATINDEX('%[^()]%',field),LEN(field)-PATINDEX('%[^()]%',field)+1))),LEN(REVERSE(SUBSTRING(field,PATINDEX('%[^()]%',field),LEN(field)-PATINDEX('%[^()]%',field)+1)))-PATINDEX('%[^()]%',REVERSE(SUBSTRING(field,PATINDEX('%[^()]%',field),LEN(field)-PATINDEX('%[^()]%',field)+1)))+1))

WHERE field LIKE '(%' or field LIKE ')%' or field LIKE '%)' or field LIKE '%('

There is a much shorter way using STUFF, REVERSE, and PATINDEX, but I thought of this way first.

|||

The remove method did the ticket. Thank you so much.

sql

No comments:

Post a Comment