Go Premium for a chance to win a PS4. Enter to Win

x
Solved

# sql question

Posted on 2008-10-03
Medium Priority
203 Views
I need an SQL that will change all rows of a field of a table that ends in 'CC' to 'C'

D215CC
End with this:
D215C
0
Question by:thenrich
• 3

LVL 32

Expert Comment

ID: 22637287
This will do it:

UPDATE MyTable
SET MyField = Left(MyField, Len(MyField)-1)
WHERE MyField LIKE '%CC'

Test by running this SELECT:

SELECT MyField, Left(MyField, Len(MyField)-1)
FROM MyTable
WHERE MyField LIKE '%CC'
0

LVL 5

Author Comment

ID: 22637391
What would I do if I wanted to 'CT' to 'P' ?
0

LVL 32

Accepted Solution

Brendt Hess earned 2000 total points
ID: 22637432
Something like this:

UPDATE MyTable
SET MyField = Left(MyField, Len(MyField)-2) + 'P'
WHERE MyField LIKE '_%CT'

Test by running this SELECT:

SELECT MyField, Left(MyField, Len(MyField)-2) + 'P'
FROM MyTable
WHERE MyField LIKE '_%CT'

NOTE:  The underscore is a tweak that ensures it is not replacing a record with only 'CT' in the field with a value of 'P'.
0

LVL 32

Expert Comment

ID: 22637470
You also have an alternate possibility using the STUFF command.  This version works for any arbitrary value and replacement, and uses variables to hold the search and replace values:

DECLARE @SearchFor varchar(10)
DECLARE @ReplaceWith varchar(10)

SET @SearchFor = 'CT'
SET @Replace = 'P'

UPDATE MyTable
SET MyField = STUFF(MyField, Len(MyField) - Len(@SearchFor), Len(@SearchFor), @Replace)
FROM MyTable
WHERE MyField LIKE '%' + @SearchFor

Test this with the code:

DECLARE @SearchFor varchar(10)
DECLARE @ReplaceWith varchar(10)

SET @SearchFor = 'CT'
SET @Replace = 'P'

SELECT MyField, STUFF(MyField, Len(MyField) - Len(@SearchFor), Len(@SearchFor), @Replace)
FROM MyTable
WHERE MyField LIKE '%' + @SearchFor
0

## Featured Post

Question has a verified solution.

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

by Mark Wills PIVOT is a great facility and solves many an EAV (Entity - Attribute - Value) type transformation where we need the information held as data within a column to become columns in their own right. Now, in some cases that is relatively…
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…
Despite its rising prevalence in the business world, "the cloud" is still misunderstood. Some companies still believe common misconceptions about lack of security in cloud solutions and many misuses of cloud storage options still occur every day. …
###### Suggested Courses
Course of the Month10 days, 22 hours left to enroll