Solved

replace the string in SQL

Posted on 2013-11-08
3
284 Views
Last Modified: 2013-11-10
I have column like below

co1

a,b,c,d,e,f
a,b,d,e,f,c,c,c
b,a,e,c,b,z,a,a

I need as

b,d,e,f
b,d,e,f
b,d,e,f
b,e,b,z

I just need to remove a and c from the column and comma if any.
0
Comment
3 Comments
 
LVL 13

Expert Comment

by:Jesus Rodriguez
ID: 39635038
UPDATE YOUR_TABLE
SET COL1=replace(replace(replace(col1,'a',''),'b',''),',,')

-- removing when star in ',' after the update
UPDATE YOUR_TABLE
SET COL1=SUBSTRING(2,LEN(COL1)-1)
WHERE LEFT(COL1,1)=',')

-- removing when ends in ',' after the update
UPDATE YOUR_TABLE
SET COL1=LEFT(COL1,LEN(COL1)-1)
WHERE RIGHT(COL1,1)=',')
0
 
LVL 5

Author Comment

by:VIVEKANANDHAN_PERIASAMY
ID: 39635088
Can't we get it in one SQL statement?
0
 
LVL 48

Accepted Solution

by:
PortletPaul earned 500 total points
ID: 39635240
/* The following would not alter co1 if it is equal to 'a' or equal to 'c' */

update table1
set col1 = replace( replace( replace( replace(co1,'a,','') ,'c,','') ,',a','') ,',c','')
;

/* the following will alter co1 if it is equal to 'a' or equal to 'c' */

update table1
set col1 = replace( replace( replace( replace( replace( replace(co1,'a,','') ,'c,','') ,',a','') ,',c','') ,'a','') ,'c','')
;

Open in new window

0

Featured Post

Migrating Your Company's PCs

To keep pace with competitors, businesses must keep employees productive, and that means providing them with the latest technology. This document provides the tips and tricks you need to help you migrate an outdated PC fleet to new desktops, laptops, and tablets.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article I will describe the Detach & Attach method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
Viewers will learn how to use the UPDATE and DELETE statements to change or remove existing data from their tables. Make a table: Update a specific column given a specific row using the UPDATE statement: Remove a set of values using the DELETE s…

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question