Application of sql loop statement in update

Application of sql loop statement in update

In actual development scenarios, we sometimes need to modify all the data in the table in batches, but when the amount of data is very large, such as millions of tens of millions of data, it will be long when we execute the update statement. Time to lock the table. This is very easy to cause deadlock phenomenon (in the enterprise DBA is definitely not allowed to execute this kind of SQL statement). Therefore, in order to avoid this kind of problem, we must modify the statements in batches when we execute the batch modification. Only a small amount of data can be modified at a time to avoid occupying the table for a long time. So in order to deal with this kind of scenario, you can use the while syntax of the following database to execute the update statement in a loop.

Now I use an example of a scenario to implement the loop operation:

Suppose we have a table User (the primary key is id):

name sex
Gang Mou male
Dongmou male
Luo Mou male

There are a million pieces of data. At this time, the evil product suddenly came to a demand. It needs to be realized that one more field new_status (status) needs to be added to the table, and the historical data is all set to 1.

At this time, the database statement is executed:


-- 在user表中添加字段 status
alter table user add new_status int ; 

begin

declare @start int  -- 定义变量 start
declare @end int	--  定义变量 end
declare @maxId int  --  定义变量 maxId (主键最大值)

set @start = 1
set @end = 100000  -- 循环体每次执行1万条数据
set @maxId = (select max(id) from user)  -- user表中最大值

-- 循环体开始
while @start < @maxId 

begin 
-- 循环体内需要执行的 SQL 语法
update user set new_status = 1 where id between @start and @start + @end
set @start = @start + @end 
end 
--循环体结束

end 

This kind of loop syntax is suitable for many scenarios, this is just one of them, I hope my sharing will be helpful for some new database development

Guess you like

Origin blog.csdn.net/fei476662546/article/details/108753217