在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
答案 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');