Declare mariaDB error. How can fix this query?

368 Views Asked by At

I'm trying to fill a table with some columns from another table giving an id, but I got this error:

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 'type of products.CategoryID; DECLARE t_productid type of products.ProductID;' at line 4

I don't know how to fix it, I hope you can help me.

 DELIMITER //
 Create procedure getProducts(v_categoryid int)
 BEGIN
    DECLARE done INT DEFAULT FALSE;
    DECLARE t_categoryid type of products.CategoryID;
    DECLARE t_productid type of products.ProductID;
    DECLARE t_productname type of products.ProductName;
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
    DECLARE cur1 CURSOR(p_categoryid int)
    FOR
    SELECT CategoryID, ProductID, ProductName 
    FROM products
    WHERE CategoryID = p_categoryid; 

    create table IF NOT exists curProducts(
    CategoryID int(10),
    ProductID int(10),
    ProductName varchar(40));

    truncate table curProducts;
    open cur1(v_categoryid);
    read_loop: LOOP
       FETCH cur1 INTO t_categoryid, t_productid, t_productname;
       IF done THEN
          LEAVE read_loop;
       END IF;
       INSERT INTO curProducts VALUES (t_categoryid, t_productid, t_productname);
    END LOOP;
    close cur1;

    select * from curProducts;
END // 
DELIMITER ;
2

There are 2 best solutions below

1
On BEST ANSWER

You can use explicit types, or upgrade to mariadb-10.3 where the TYPE OF syntax was introduced.

2
On

This solution avoids the syntax error by not needing those statements!

DECLARE done INT DEFAULT FALSE;
DECLARE t_categoryid type of products.CategoryID;
DECLARE t_productid type of products.ProductID;
DECLARE t_productname type of products.ProductName;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
DECLARE cur1 CURSOR(p_categoryid int)
FOR
SELECT CategoryID, ProductID, ProductName 
FROM products
WHERE CategoryID = p_categoryid; 

open cur1(v_categoryid);
read_loop: LOOP
   FETCH cur1 INTO t_categoryid, t_productid, t_productname;
   IF done THEN
      LEAVE read_loop;
   END IF;
   INSERT INTO curProducts VALUES (t_categoryid, t_productid, t_productname);
END LOOP;
close cur1;

All of that can be replaced by merely

INSERT INTO curProducts VALUES (t_categoryid, t_productid, t_productname)
    SELECT CategoryID, ProductID, ProductName 
    FROM products
    WHERE CategoryID = p_categoryid;