I'm trying to make a list of the numbers 1-1000 for a HackerRank exercise in MySQL, version (as far as I can discover) 5.7.
Here's my code:
create table numeros
(
numero int not null auto_increment,
primary key (numero)
);
loop
insert into numeros () values ();
if max(numeros.numero) = 1000 then leave; end if;
end loop;
select * from numeros
I'm getting this error:
ERROR 1064 (42000) at line 6: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'loop
insert into numeros () values ()' at line 1
What am I doing wrong? How can I make this loop work?
I'm trying to make a list of the numbers 1-1000 for a HackerRank exercise in MySQL, version (as far as I can discover) 5.7.
Here's my code:
create table numeros
(
numero int not null auto_increment,
primary key (numero)
);
loop
insert into numeros () values ();
if max(numeros.numero) = 1000 then leave; end if;
end loop;
select * from numeros
I'm getting this error:
ERROR 1064 (42000) at line 6: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'loop
insert into numeros () values ()' at line 1
What am I doing wrong? How can I make this loop work?
Share Improve this question edited Mar 6 at 15:46 Filburt 18.1k13 gold badges90 silver badges149 bronze badges asked Mar 6 at 15:12 user29916678user29916678 11 4 |1 Answer
Reset to default 0You can't use mySQL group function that way ...
You may use a simple counter to do this:
create table numeros
(
numero int not null auto_increment,
primary key (numero)
);
CREATE PROCEDURE autoIncreant()
BEGIN
declare c INT default 0;
loop_name: loop
insert into numeros () values ();
set c=c+1;
if c = 1000 then
leave loop_name;
end if;
end loop;
END ;
call autoIncreant();
select * from numeros;
db-fiddler Sample code
Alternative way:
CREATE PROCEDURE autoIncreant()
BEGIN
loop_name: loop
insert into numeros () values ();
select @c := MAX(numero) from numeros;
if @c = 1000 then
leave loop_name;
end if;
end loop;
END ;
db-fiddler sample code2
IF
,LOOP
,WHILE
) are only allowed in stored procedures. – Barmar Commented Mar 6 at 15:37mysql.help_relation
) or 2-3 copies of such table as a rowsource and user-defined variable as iterator. – Akina Commented Mar 6 at 16:59