Search code examples
mysqlsqlinnodbdelimiter

How to create a procedure to insert which returns the inserted row


Here is my current SQL:

CREATE PROCEDURE addBlog(@title VARCHAR(255), @body VARCHAR(255), OUT @uuid INT) BEGIN
    INSERT INTO blogs b (b.title, b.detail) VALUES (@title, @body);
    SELECT LAST_INSERT_ID() INTO @uuid;
    SELECT @uuid;
END

Which is throwing this error (directly from SQL export):

1064 - 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 '@title VARCHAR(255), @body VARCHAR(255), OUT @uuid INT) BEGIN INSERT INTO blog' at line 1

My Database has an AUTO_INCREMENT PRIMARY KEY on uuid INT (255) which I want to return using this procedure. Any help would be great.

My table looks like this:

CREATE TABLE `blogs` (
  `uuid` int(255) NOT NULL,
  `title` varchar(1024) NOT NULL,
  `detail` varchar(1024) NOT NULL,
  `user_id` int(255) NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `blogs`
  ADD PRIMARY KEY (`uuid`),
  ADD KEY `user_id` (`user_id`);

ALTER TABLE `blogs`
  MODIFY `uuid` int(255) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;

ALTER TABLE `blogs`
  ADD CONSTRAINT `blogs_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` 
(`uuid`) ON DELETE NO ACTION ON UPDATE NO ACTION;

UPDATED SQL:

CREATE PROCEDURE addBlog(
    IN in_title VARCHAR(255),
    IN in_body VARCHAR(255), 
    IN in_user INT(255),
    OUT out_uuid INT
) BEGIN
    INSERT INTO `blogs` (`title`, `detail`, `user_id`) VALUES (in_title, in_body, in_user);
    SELECT LAST_INSERT_ID() INTO out_uuid;
    SELECT out_uuid;
END;

Solution

  • You are missing parameter type definition such as IN, OUT etc. Also, I don't think you need to use @, in parameter definition.

    Also, I like to ensure that name of the variables/parameters in a Stored Procedure / Trigger etc, are different from any of the table/column name(s) used in them.

    Also, if you haven't done it already, you need to redefine Delimiter to something else (like, $$) other than ;; and redefine it back to ; at the end.

    DELIMITER $$ -- define the delimiter
    
    CREATE PROCEDURE addBlog(IN title_in VARCHAR(255), -- added suffix "in" to param name
                             IN body_in VARCHAR(255), 
                             OUT uuid_out INT) BEGIN
    ...... 
    
    END $$ -- end of stored procedure
    DELIMITER ; -- redefine delimiter back to ;