Question

I would like to create a table (two columns, first is auto incremental) which contains the term names, e.g. "SS 2000" and "WS 2000/2001" (for summer and winter term).

I tried the following:

CREATE PROCEDURE create_terms()
BEGIN
Declare @YearEnd integer;
SET @YearEnd = 2014;
Declare @YearFrom integer = @YearEnd - 100;
Declare @Term varchar = '';
while @YearFrom < @YearEnd Begin
    @Term = concat('SS ', @YearFrom);
  Insert into terms (term) VALUES @Term;
  Set @YearFrom = @YearFrom + 1;
End
END

but I already get an error in line 3: SQL query:

CREATE PROCEDURE create_terms() BEGIN Declare @YearEnd integer;

MySQL said: Documentation #1064 - 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 '@YearEnd integer' at line 3

After reading the comments from Abishek and Stuart, I tried the following:

DELIMITER $$ 
DROP PROCEDURE IF EXISTS create_terms$$ 
CREATE PROCEDURE create_terms()
BEGIN
  DECLARE YearEnd INT;
  Declare YearFrom INT;
  Declare Term varchar(10);

  SET YearEnd = 2014;
  SET YearFrom = YearEnd - 100;
  SET Term= '';

WHILE (YearFrom < YearEnd) DO
  SET Term = concat('SS ', YearFrom);
  Insert into terms (term) VALUES (Term);
  Set YearFrom = YearFrom + 1;
 END WHILE;
END;

DELIMITER ;

This results in just the DROP PROCEDURE command being successfully processed. Even when removing this line and changing the first lines to:

 DELIMITER $$ 
 CREATE PROCEDURE create_terms()$$
 BEGIN

it doesn't work, the SQl console just writes "ERROR" and that's it.... :(

Was it helpful?

Solution

There are quite a bunch of errors here

  • You should use procedure variables
  • The Syntax for insert is INSERT INTO Table(columns) VALUES(values);
  • You probably also want to insert the term, not the year end
  • Your syntax for while is wrong

CREATE PROCEDURE create_terms()
BEGIN
  DECLARE YearEnd INT;
  Declare YearFrom INT;
  Declare Term varchar(10);

  SET YearEnd = 2014;
  SET YearFrom = YearEnd - 100;
  SET Term= '';

  WHILE (YearFrom < YearEnd) DO
      SET Term = concat('SS ', YearFrom);
      Insert into terms (term) VALUES (Term);
      Set YearFrom = YearFrom + 1;
  END WHILE;
END

Fiddle here

OTHER TIPS

All variable staring @ are user variables and need not to be declared, procedures has their local variables not prefix with @, try like this:

DELIMITER $$
DROP PROCEDURE IF EXISTS create_terms$$
CREATE PROCEDURE create_terms()
BEGIN
Declare YearEnd integer;
SET YearEnd = 2014;
Declare YearFrom integer = YearEnd - 100;
Declare Term varchar = '';
while YearFrom < YearEnd Begin
    Term = concat('SS ', YearFrom);
  Insert into terms (term) VALUES YearFrom;
  Set YearFrom = YearFrom + 1;
End;
END;
DELIMITER ;

Here is help

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top