MySQL过程变量在计数(*)时接收空值

3bygqnnd  于 2023-01-04  发布在  Mysql
关注(0)|答案(1)|浏览(115)

为什么当我执行Select count(*) From table1时,我得到300,但如果我执行SELECT end = COUNT(*) FROM table1;,则返回null
下面是小提琴示例https://dbfiddle.uk/ZHzoaztV
代码片段:

CREATE TABLE table1(
  start int NOT NULL,
  id int PRIMARY KEY AUTO_INCREMENT,
  counter int NOT NULL,
  difference int NOT NULL,
  end int NOT NULL
);

CREATE PROCEDURE doWhile()
BEGIN
  DECLARE i INT DEFAULT 1;
  DECLARE start INT DEFAULT 120;
  DECLARE counter INT DEFAULT 1;
  DECLARE end INT DEFAULT 300;
WHILE (i <= end) DO
  INSERT INTO table1 VALUES (start,null,counter,start+counter,end); 
  SET i = i+1;
  SET counter = counter+1;
END WHILE;
END;
CALL doWhile();
SELECT * FROM table1;

CREATE PROCEDURE insertMore()
BEGIN
  DECLARE start INT;
  DECLARE counter INT DEFAULT 1;
  DECLARE end INT;

  SELECT end = COUNT(*) FROM table1;
  SELECT start = MAX(id)+1 FROM table1;
  -- SELECT COUNT(*) FROM table1;

  WHILE (counter <= end) DO
    INSERT INTO table1 VALUES (start,null,counter,start+counter,end); 
    SET counter = counter+1;
  END WHILE;
END;
CALL insertMore();
SELECT * FROM table1;

我期望返回300,所以希望我的函数能正确地执行该操作

ws51t4hk

ws51t4hk1#

开始变量和结束变量有问题
你能试试这个吗:

CREATE PROCEDURE insertMore()
BEGIN
  DECLARE start INT;
  DECLARE counter INT DEFAULT 1;
  DECLARE end INT;

  SELECT COUNT(*) into end FROM table1;
  SELECT max(id)+1 into start FROM table1;
  -- SELECT COUNT(*) FROM table1;

  WHILE (counter <= end) DO
    INSERT INTO table1 VALUES (start,null,counter,start+counter,end); 
    SET counter = counter+1;
  END WHILE;
END;

在这里试试:https://dbfiddle.uk/X6vP3wKW

相关问题