0

I am using a while loop in a stored procedure to update each row of my table but the update value remains the same for all rows.For instance,in my table the generated number is 2266 for all rows instead of a unique digit.

My stored procedure looks like this

DELIMITER ;;
CREATE PROCEDURE lesrows()
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
DECLARE lesrand INT DEFAULT 0;
SELECT COUNT(*) FROM students INTO n;
select(FLOOR(2000 + RAND() * (3000 - 2000) )) into lesrand;
SET i=0;
WHILE i<n DO 
  UPDATE students set student_number= lesrand;
  SET i = i + 1;
END WHILE;
End;
;;

call lesrows();

Why is it inserting a constant number for all rows instead of a unique number for every row?.

4

2 回答 2

4

while 语句在每次迭代中将整个表的 student_number 设置为 lesrand。您想要每次迭代的新随机数(在循环内),并且您想要使用 WHERE 和变量 i 一个一个地选择学生

像这样的东西:

SET i=0;
WHILE i<n DO 
select(FLOOR(2000 + RAND() * (3000 - 2000) )) into lesrand;      
UPDATE students set student_number= lesrand WHERE student_ID = i;
SET i = i + 1;
END WHILE;
于 2013-07-29T08:39:08.153 回答
0

我还没有测试过,但看起来 lesrand 只分配了一次。您是否尝试过select(FLOOR(2000 + RAND() * (3000 - 2000) )) into lesrand;像这样进入 while 循环:

DELIMITER ;;
CREATE PROCEDURE lesrows()
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
DECLARE lesrand INT DEFAULT 0;
SELECT COUNT(*) FROM students INTO n;
SET i=0;
WHILE i<n DO 
  select(FLOOR(2000 + RAND() * (3000 - 2000) )) into lesrand;
  UPDATE students set student_number= lesrand;
  SET i = i + 1;
END WHILE;
End;
;;

call lesrows();

以及为什么要使用存储过程。不会UPDATE students SET student_number = FLOOR(2000 + RAND() * (3000 - 2000))有同样的结果吗?

于 2013-07-29T08:40:12.560 回答