Link to home
Start Free TrialLog in
Avatar of kloner
kloner

asked on

SQL update column via loop

Simple really

Need to update a column's value, by appending 1 to a counter and adding a string to it ...

SQL code should explain it all ...
-- Grab the max ext_ref_id and add one.
DECLARE @MAX_EXT_REF_ID AS INTEGER
 
SELECT @MAX_EXT_REF_ID = MAX(CAST(REPLACE(EXT_REF_ID, '_BLC', '') AS INTEGER)) + 1 
FROM [TBL_BLUECARE_CANDIDATES] 
WHERE [EXT_REF_ID] like '%_BLC'
 
SELECT @MAX_EXT_REF_ID -- RETURNS 78656
 
 
--SELECT ALL USERS THAT DO NOT HAVE '_BLC' in the [EXT_REF_ID]
SELECT [EXT_REF_ID]
FROM   [TBL_BLUECARE_CANDIDATES]
WHERE  [EXT_REF_ID] not like '%_BLC'
ORDER BY [EXT_REF_ID]
 
/* RETURNS DATA LIKE 
 
000
0001
001
002
003003003
007
01
079091
10661
11101110
11986
121212123
12335
1234
 
*/
 
 
-- NEED TO UPDATE ALL [EXT_REF_ID] WITHOUT '_BLC' and APPEND @MAX_EXT_REF_ID + 1 + '_BLC'
--  eg. 78656_BLC
--  eg. 78657_BLC
--  eg. 78658_BLC
--  eg. 78659_BLC
 
BEGIN LOOP 
	FOR EACH RECORD IN QUERY ABOVE
	UPDATE [EXT_REF_ID] = (@MAX_EXT_REF_ID + 1) + '_BLC'
END LOOP

Open in new window

SOLUTION
Avatar of BrandonGalderisi
BrandonGalderisi
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of kloner
kloner

ASKER

I forgot to mention ... some of the existing [EXT_REF_ID] data that we are trying to update actually contains dulpicate data ... hence we can't rely on the join statement you suggested ... on bcc.ext_ref_id = r.ext_ref_id

.......

Current output dump:

000
000
0001
001
001
001
002
003003003
007
01
079091
10661
11101110
11986
11986
So 001, 001, 001 would all need to be new records.  What is the PK of the table?
Avatar of kloner

ASKER

Well you won't believe this ... ther's no bloody PK in this OLD DB ... I can just get the duplicate records and manually update them hey as a quick win ...
You should add an identity column and make it your PK.  I assume you don't have a clustered index either?
It seems like that's what you are trying to do with the ext_ref_id.
ASKER CERTIFIED SOLUTION
Avatar of Zberteoc
Zberteoc
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial