SQL:使用术语名称创建表(包含年份的字符串)

时间:2014-05-05 08:21:40

标签: mysql sql stored-procedures

我想创建一个表(两列,第一列是自动增量),其中包含术语名称,例如: " SS 2000"和" WS 2000/2001" (夏季和冬季学期)。

我尝试了以下内容:

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

但我在第3行已经收到错误:SQL查询:

CREATE PROCEDURE create_terms() 开始     声明@YearEnd整数;

MySQL说:文档#1064 - 你的SQL语法有错误;检查与您的MySQL服务器版本对应的手册,以获得正确的语法,以便使用&#39; @YearEnd integer&#39;在第3行

在阅读Abishek和Stuart的评论后,我尝试了以下内容:

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 ;

这导致仅成功处理DROP PROCEDURE命令。即使删除此行并将第一行更改为:

 DELIMITER $$ 
 CREATE PROCEDURE create_terms()$$
 BEGIN

它不起作用,SQl控制台只是写&#34; ERROR&#34;那就是...... :(

2 个答案:

答案 0 :(得分:1)

所有变量凝视@都是用户变量,不需要声明,过程的局部变量不是@的前缀,请尝试这样:

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是帮助

答案 1 :(得分:1)

这里有很多错误

  • 您应该使用procedure variables
  • 插入语法为INSERT INTO Table(columns) VALUES(values);
  • 您可能还想插入术语,而不是年末
  • 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