Syntax Error declaring variables in MariaDB

Nimetski :

I have a problem with the following query:

START TRANSACTION;
INSERT INTO posts
(
-- not relevant
)
VALUES
(
-- insert works as intended
);
COMMIT WORK AND CHAIN;

DECLARE @insertId INT; -- this is where i get the syntax error
SET @insertId = LAST_INSERT_ID();

UPDATE posts
SET guid = CONCAT('foo.bar?p=', @insertId)
WHERE id = @insertId;

-- continue to work with the variable
INSERT INTO postmeta(post_id, key, value)
VALUES
(@insertId, ..., ...),
(@insertId, ..., ...),
(@insertId, ..., ...),
(@insertId, ..., ...);
COMMIT WORK;

Basically I insert a row, and need to update it, using the auto incremented id immediately after the insert (to make sure I get the correct value out of the function LAST_INSERT_ID). Then I need to fill an other table, also using the auto incremented id. In this use case I figured, that I need to store the value in a variable. Why do i get the following error message? "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'DECLARE @insertId INT; SET @insertId = LAST_INSERT_ID();' at line 1" Is the problem that I don't create a procedure or user defined function?

dylenv :

I did a quick search and found this on the MariaDB website (https://mariadb.com/kb/en/user-defined-variables/):

"Since user-defined variables type cannot be declared, the only way to force their type is using CAST() or CONVERT()"

I think the solution is just removing the declare statement since there are examples on their site making variables without declaring them.

I hope this works, I'm not really familiar with MariaDB!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=23625&siteId=1