DECLARE上的语法错误

时间:2014-09-02 09:55:03

标签: mysql syntax

我想在下一个插入中直接使用插入序列。

基于Help with T-SQL script: Insert record, then use identity of that insert on another statement?我执行以下SQL查询:

DECLARE @Id1 BIGINT
DECLARE @Id2 BIGINT
INSERT INTO doses (CPS, ground, total) VALUES (10, 10, 10)
SET @Id1 = SELECT SCOPE_IDENTITY()
INSERT INTO places (x, y, z, speed) VALUES (10, 10, 10, 10)
SET @Id2 = SELECT SCOPE_IDENTITY()
INSERT INTO measurements (time, place, note, dose, id_dataset) VALUES ('Test', @Id1, 'test', @Id2, 17)

这给我一个语法错误,我发现我的DECLARE没有任何问题。

#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 'DECLARE @Id1 BIGINT
DECLARE @Id2 BIGINT INSERT INTO doses (CPS, ground, total)' at line 1 

似乎MySQL中的DECLARE只能用于BEGIN..END。 http://dev.mysql.com/doc/refman/5.0/en/declare.html

另外,SCOPE_IDENTITY将替换为LAST_INSERT_ID()。

这是我的新查询:

BEGIN

DECLARE @Id1 BIGINT;
DECLARE @Id2 BIGINT;

INSERT INTO doses (CPS, ground, total) VALUES (10, 10, 10);
SET @Id1 = (SELECT LAST_INSERT_ID());

INSERT INTO places (x, y, z, speed) VALUES (10, 10, 10, 10);
SET @Id2 = (SELECT LAST_INSERT_ID());

INSERT INTO measurements (time, place, note, dose, id_dataset);
VALUES ('Test', @Id1, 'test', @Id2, 17);

END

但我仍然得到同样的错误。

3 个答案:

答案 0 :(得分:1)

似乎you cannot declare and use variables outside triggers/procedures/functions or events。因此,您只需在其周围编写BEGIN...END即可解决此问题。

由于在一个select语句中需要两个不同的ID值,您可以将其包装到存储过程中(这应该避免无法声明变量的问题)或者只使用MAX - 值最终insert-statement中两列中的ID。 (当然这假设您在两个表中都启用了auto_increment或至少提升了ID)

所以从本质上说,如果你用以下代码替换整个代码,你应该能够使它工作:

INSERT INTO doses (CPS, ground, total) VALUES (10, 10, 10);

INSERT INTO places (x, y, z, speed) VALUES (10, 10, 10, 10);

INSERT INTO measurements (time, place, note, dose, id_dataset)
VALUES ('Test', (SELECT MAX(ID) FROM doses), 'test', (SELECT MAX(ID) FROM places), 17);

您还应该将此包装在一个事务中,以确保在此期间没有插入其他ID。

答案 1 :(得分:0)

它只是一个语法错误。

SELECT @ ID1 = SCOPEIDENTITY()我认为

答案 2 :(得分:-1)

设置@ Id1和@ Id2

似乎存在问题
    DECLARE @Id1 BIGINT
    DECLARE @Id2 BIGINT

    INSERT INTO doses (CPS, ground, total) VALUES (10, 10, 10)
    SET @Id1 = SCOPE_IDENTITY()

    INSERT INTO places (x, y, z, speed) VALUES (10, 10, 10, 10)
    SET @Id2 =SCOPE_IDENTITY()

    INSERT INTO measurements (time, place, note, dose, id_dataset) 
    VALUES ('Test', @Id1, 'test', @Id2, 17)