Update substring of a column

2019-02-11 21:51发布

问题:

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.

回答1:

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_\%'


回答2:

MYSQL:

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