Forum Discussion
Angene_Thompson
Oct 04, 2023Copper Contributor
Updating records using while loop
The below code keeps overwriting the data even though I made the id of the record equal to the counter.
declare @count int;
declare @counter int;
set @count = (select count(* ) from users);
set @counter = 1;
while @counter <= @count
BEGIN
update users
set email = (select REPLACE(email,substring(email,1,charindex('@',email)-1), lower(u_name))
FROM users WHERE id = @counter)
set @counter = @counter + 1
END
- add the where clause again after FROM users WHERE id = @counter) :
declare @count int;
declare @counter int;
set @count = (select count(* ) from users);
set @counter = 1;
while @counter <= @count
BEGIN
update users
set email = (select REPLACE(email,substring(email,1,charindex('@',email)-1), lower(u_name))
FROM users WHERE id = @counter)
WHERE id = @counter
set @counter = @counter + 1
END
2 Replies
- Paula_PCopper Contributoradd the where clause again after FROM users WHERE id = @counter) :
declare @count int;
declare @counter int;
set @count = (select count(* ) from users);
set @counter = 1;
while @counter <= @count
BEGIN
update users
set email = (select REPLACE(email,substring(email,1,charindex('@',email)-1), lower(u_name))
FROM users WHERE id = @counter)
WHERE id = @counter
set @counter = @counter + 1
END- Angene_ThompsonCopper ContributorIt works. Thanks.