[] How to modify data of a table in batches in sqlserver, 2015 sqlserver
During the past few days of exercises, I encountered a small problem. For example, if I had a score initialized to 0 in all the tables, I want to randomly generate less than 100 of the data and write it in. What should I do? Just use a few small functions,
One is rand ()
It generates random numbers.
One is cast ()
It is responsible for type conversion.
One is round ()
It is responsible for rounding values. In addition, floor () indicates the downward value, while ceiling () indicates the upward value.
Next, we need to create a temporary table # temp.
select identity(int,1,1) id, * into temp from score
Note that the id column is added by myself. If your table contains a primary key and is not a primary key combination, you do not need to add the id column.
In fact, the central idea of modifying data in a table in batches is to remember that the table has a self-increasing column. If there is one, it would be best. If not, create a temporary table, let the temporary table have such a column and connect the two tables. After the connection, each item has an auto-incrementing column, and then sets a temporary variable to compare it with the auto-incrementing column. Then, based on the value of the edge variable, modify Table data in one row.
Not clear, just add a piece of code.
declare @total int,@cur int select @total=count(*)from #tempset @tot=1WHILE @tot<=@total beginupdate score set chengji= cast(100*rand()as int)from score t1,#temp t2where t1.stu=t2.stuand t1.course=t2.courseand t2.id=@curset @tot=@tot+1end
You can understand what the code means.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.