使用IF语句创建SQL存储过程

时间:2013-03-23 14:56:48

标签: mysql sql

我正在尝试在PHPmyadmin中创建一个存储过程,但它似乎不喜欢我的IF语句。任何人都可以帮我确定我做错了什么:

SQL:

CREATE PROCEDURE get_products_in_category(IN inCategoryID INT, 
IN inShortDescriptionLength INT, IN inProductsPerPage INT, IN inStartItem INT)

BEGIN
"SELECT p.productID, p.name, IF(LENGTH(p.description) <= ?, p.description, 
 CONCAT(LEFT(p.description, ?), '...')) AS description, p.price, p.discounted_price, 
 p.thumbnail FROM tblProducts p

INNER JOIN tblProdCat pc
ON pc.productID = p.productID
WHERE tblProdCat.categoryID = ?
ORDER BY p.display DESC
LIMIT ?, ?";

SET @p1 = inShortDescriptionLength;
SET @p2 = inShortDescriptionLength;
SET @p3 = inCategoryID;
SET @p4 = inStartItem;
SET @p5 = inProductsPerPage;

END$$

我收到以下错误:

  

您的SQL语法有错误;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   ''SELECT p.productID,p.name,IF(LENGTH(p.description)&lt; =?)附近   p.description,CONCA'在第3行

1 个答案:

答案 0 :(得分:0)

我认为你想要执行动态SQL

DELIMITER $$
CREATE PROCEDURE get_products_in_category
(
    IN inCategoryID INT, 
    IN inShortDescriptionLength INT, 
    IN inProductsPerPage INT, 
    IN inStartItem INT
)
BEGIN

    SET @sql = CONCAT('SELECT   p.productID, 
                                p.name, 
                                IF(CHAR_LENGTH(p.description) <= ?, p.description, CONCAT(LEFT(p.description, ?), ''...'')) AS description, 
                                p.price, 
                                p.discounted_price, 
                                p.thumbnail 
                        FROM    tblProducts p
                                INNER JOIN tblProdCat pc
                                    ON pc.productID = p.productID
                        WHERE   pc.categoryID = ?
                        ORDER   BY p.display DESC
                        LIMIT   ',inStartItem, ', ',inProductsPerPage);



    PREPARE stmt1 FROM @sql;
    SET @p1 = inShortDescriptionLength;
    SET @p2 = inShortDescriptionLength;
    SET @p3 = inCategoryID;

    EXECUTE stmt1 USING @p1, @p2, @p3;
    DEALLOCATE PREPARE stmt1;
END $$
DELIMITER ;