user2547340
user2547340

Reputation: 325

Update substring of a column

I have a table within a SQL Server 2008 database called Meter. This table has a column called Name.

Each entry within the column Name has a prefix of the following ZAA\. I'd like to change this prefix to ZAA_ without affecting the rest of the text within the column.

Upvotes: 26

Views: 110106

Answers (3)

user2823361
user2823361

Reputation: 111

MYSQL:

UPDATE Meter
SET Name = CONCAT('ZAA' ,'_', SUBSTRING(Name, 4, LENGTH(Name)))
WHERE Name LIKE 'ZAA\%'

Upvotes: 3

Romesh
Romesh

Reputation: 2274

Here is the SQLFiddel Demo

Below is the Query which you can try

CREATE TABLE Meter
    ([Name] varchar(7))
;

INSERT INTO Meter
    ([Name])
VALUES
    ('ZAA\001')
;


select * from Meter;

Update Meter
   set Name = stuff(Name,4,1,'_')
 Where SUBSTRING(Name, 1,4) ='ZAA' + Char(92);

select * from Meter;

Upvotes: 2

Darren
Darren

Reputation: 70748

UPDATE Meter
SET Name = 'ZAA_' + SUBSTRING(Name, 4, LEN(Name))
WHERE SUBSTRING(Name, 1, 4) = 'ZAA\'

Edit:

Or as @Damien_The_Unbliever states, to use an index:

UPDATE Meter
SET Name = 'ZAA_' + SUBSTRING(Name, 4, LEN(Name))
WHERE Name LIKE 'ZAA\%'

EDIT

From your comment, try this statement to fix the additional \:

UPDATE Meter
SET Name = 'ZAA_' + SUBSTRING(Name, 5, LEN(Name))
WHERE Name LIKE 'ZAA_\%'

Upvotes: 32

Related Questions