Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update substring of a column

Tags:

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.

like image 492
user2547340 Avatar asked Sep 02 '13 10:09

user2547340


People also ask

How do you update a substring of a column in SQL?

You can use the SUBSTR operator to get a substring from a field. For example, to get bytes 3-7 of a field called MYNAME, use the expression SUBSTR(MYNAME,3,5). You can update part of a character field by concatenating the parts you want to stay intact with the new value.

How do you update part of a string?

Update Part of a String in SQL Using the REPLACE() Function We could have done this simpler by using the REPLACE() function. It replaces all occurrences of a specified string value with another string value. The REPLACE function returns a string where it replaces a substring with another substring.

How do you update a column in another column in SQL?

UPDATE table SET col = new_value WHERE col = old_value AND other_col = some_other_value; UPDATE table SET col = new_value WHERE col = old_value OR other_col = some_other_value; As you can see, you can expand the WHERE clause as much as you'd like in order to filter down the rows for updating to what you need.


2 Answers

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_\%' 
like image 104
Darren Avatar answered Sep 23 '22 06:09

Darren


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; 
like image 31
Romesh Avatar answered Sep 23 '22 06:09

Romesh