调用时存储过程错误

时间:2013-08-28 05:38:04

标签: mysql sql stored-procedures

当我调用我的程序时,它会返回错误:

  

1064 - 您的SQL语法出错;检查与MySQL服务器版本对应的手册,以便在第1行的“NULL”附近使用正确的语法

如何修复它,我的程序代码中是否有错误?

这是我的存储过程:

DELIMITER $$
DROP PROCEDURE IF EXISTS `gamedb`.`ALIAS#SEARCH`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `ALIAS#SEARCH`(
  in section_id varchar(255),
  in category_id varchar(255),
  in content_id varchar(255)
)

BEGIN
declare q varchar(4000);
set @q = 'SELECT * FROM tbl_alias WHERE ALIAS_ACTIVE_STATUS=1';

IF section_id IS NOT NULL THEN
  set @q = concat(q,' AND ALIAS_SECTION_ID = ',section_id);
END IF;

IF category_id IS NOT NULL THEN
  set @q = concat(q,' AND ALIAS_CATEGORY_ID = ',category_id);
END IF;

IF content_id IS NOT NULL THEN
  set @q = concat(q,' AND ALIAS_CONTENT_ID = ',content_id);
END IF;

set @q= concat(q,' ORDER BY ALIAS_ID DESC');
prepare stmt from @q;

EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;

1 个答案:

答案 0 :(得分:0)

有几个问题

  1. 由于您只能从用户变量PREPARE,因此您不需要本地变量q
  2. 使用@

    时,@q变量遗失CONCAT()
    set @q = concat(q,' AND ALIAS_SECTION_ID = ',section_id);
                    ^
    
  3. 由于您的IN参数定义为VARCHAR,因此在构建查询时最好引用其值
  4. 据说你的SP可能看起来像这样

    DELIMITER $$
    CREATE PROCEDURE `ALIAS#SEARCH`(
      in section_id varchar(255),
      in category_id varchar(255),
      in content_id varchar(255)
    )
    
    BEGIN
      SET @q = 'SELECT * FROM tbl_alias WHERE ALIAS_ACTIVE_STATUS = 1';
    
      IF section_id IS NOT NULL THEN
        SET @q = CONCAT(@q, ' AND ALIAS_SECTION_ID = ''', section_id, '''');
      END IF;
    
      IF category_id IS NOT NULL THEN
        SET @q = CONCAT(@q, ' AND ALIAS_CATEGORY_ID = ''', category_id, '''');
      END IF;
    
      IF content_id IS NOT NULL THEN
        SET @q = CONCAT(@q, ' AND ALIAS_CONTENT_ID = ''', content_id, '''');
      END IF;
    
      SET @q = CONCAT(@q, ' ORDER BY ALIAS_ID DESC');
    
      PREPARE stmt FROM @q;
      EXECUTE stmt;
      DEALLOCATE PREPARE stmt;
    END$$
    DELIMITER ;