在mysql中声明语法

时间:2012-01-19 22:41:46

标签: mysql

在mysql bench 5.2中运行此查询时,我总是遇到错误 “Declare @QuestionnaireID int附近的SQL语法错误; ................”

Begin 
  DECLARE @QuestionnaireID int;
  INSERT INTO dbo.Questionnaire VALUES('Questionnaire 1');
  SET @QuestionnaireID = SCOPE_IDENTITY();
  INSERT INTO dbo.QuestionnaireQuestion VALUES(@QuestionnaireID, 1, 'This is the first quetion');
  INSERT INTO dbo.QuestionnaireQuestion VALUES(@QuestionnaireID, 2, 'This is the second quetion'); 
  INSERT INTO dbo.QuestionnaireQuestion VALUES(@QuestionnaireID, 3, 'This is the third quetion');
  DECLARE @QuestionnaireResponseID int;
  INSERT INTO dbo.QuestionnaireResponse VALUES(@QuestionnaireID, 1, GETDATE()); 
  SET @QuestionnaireResponseID = SCOPE_IDENTITY(); 
  INSERT INTO dbo.QuestionnaireAnswer VALUES(@QuestionnaireID, 1, 1, 'This is answer to first quetion'); 
  INSERT INTO dbo.QuestionnaireAnswer VALUES(@QuestionnaireID, 1, 2, 'This is answer to second quetion');
  INSERT INTO dbo.QuestionnaireAnswer VALUES(@QuestionnaireID, 1, 3, 'This is answer to third quetion');

End

1 个答案:

答案 0 :(得分:2)

MySQL中的用户定义变量不需要声明。

此外,MySQL没有SCOPE_IDENTITY()功能。您要找的是LAST_INSERT_ID()

同样,MySQL没有GETDATE()功能,而是使用NOW()

此外,您应该显式枚举要为每个INSERT语句插入的列。例如,由于调查问卷表明显具有自动增量pk,您需要枚举要插入的列,否则插入将失败。

这是您重写的SQL,用于解决前3个问题:

INSERT INTO test.Questionnaire VALUES('Questionnaire 1'); 
SET @QuestionnaireID = LAST_INSERT_ID();

INSERT INTO test.QuestionnaireQuestion VALUES(@QuestionnaireID, 1, 'This is the first quetion'); 
INSERT INTO test.QuestionnaireQuestion VALUES(@QuestionnaireID, 2, 'This is the second quetion'); 
INSERT INTO test.QuestionnaireQuestion VALUES(@QuestionnaireID, 3, 'This is the third quetion'); 

INSERT INTO test.QuestionnaireResponse VALUES(@QuestionnaireID, 1, NOW()); 
SET @QuestionnaireResponseID = LAST_INSERT_ID();

INSERT INTO test.QuestionnaireAnswer VALUES(@QuestionnaireID, 1, 1, 'This is answer to first quetion'); 
INSERT INTO test.QuestionnaireAnswer VALUES(@QuestionnaireID, 1, 2, 'This is answer to second quetion'); 
INSERT INTO test.QuestionnaireAnswer VALUES(@QuestionnaireID, 1, 3, 'This is answer to third quetion');