I am using the code below to update about 5000 customer records to a new customer number format. Example: ABC001, ABC002, ABD001, ABD002 and so on... first 3 are chars of 3 first chars of the customer name and last 3 is incrementing number. The works great if I were to update all customer number at once and never get back to it. However about 2000 of those records were already changed manually. When this script is used I get duplicate values because some of the numbers that the script is trying to produce already exist. I'd like to change all but management wants to leave all manually updated number as it is. How can I avoid creating all this mess and have no duplicate values in the end and so I can run this script every once in a while to update whichever record have that don't follow that convention?
BEGIN TRANSACTION
UPDATE CustomersTry
SET CustomerNumber =
CASE WHEN CustomerName LIKE 'the %' THEN SUBSTRING(CustomerName, 5, 3)
WHEN CustomerName LIKE '%retire%' THEN SUBSTRING(CustomerName,10,3)
ELSE LEFT(CustomerName, 3) END
+ RIGHT('000' + (SELECT CAST(COUNT(*) AS varchar)
FROM CustomersTry
WHERE CASE WHEN CustomerName LIKE 'the %' THEN SUBSTRING(CustomerName, 5, 3)
ELSE LEFT(CustomerName, 3) END =
CASE WHEN Cust.CustomerName LIKE 'the %' THEN SUBSTRING(Cust.CustomerName, 5, 3)
ELSE LEFT(Cust.CustomerName, 3) END
AND CustomerNumber <= Cust.CustomerNumber), 3)
FROM CustomersTry Cust
SELECT * FROM CustomersTry
Order by CustomerName,CustomerNumber
BEGIN TRANSACTION
UPDATE CustomersTry
SET CustomerNumber =
CASE WHEN CustomerName LIKE 'the %' THEN SUBSTRING(CustomerName, 5, 3)
WHEN CustomerName LIKE '%retire%' THEN SUBSTRING(CustomerName,10,3)
ELSE LEFT(CustomerName, 3) END
+ RIGHT('000' + (SELECT CAST(COUNT(*) AS varchar)
FROM CustomersTry
WHERE CASE WHEN CustomerName LIKE 'the %' THEN SUBSTRING(CustomerName, 5, 3)
ELSE LEFT(CustomerName, 3) END =
CASE WHEN Cust.CustomerName LIKE 'the %' THEN SUBSTRING(Cust.CustomerName, 5, 3)
ELSE LEFT(Cust.CustomerName, 3) END
AND CustomerNumber <= Cust.CustomerNumber), 3)
FROM CustomersTry Cust
SELECT * FROM CustomersTry
Order by CustomerName,CustomerNumber