0

当我调用我的过程时,它返回一个错误:

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 ;
4

1 回答 1

0

有几个问题

  1. 由于您PREPARE只能来自用户变量,因此您不需要局部变量q
  2. @使用时缺少@q变量CONCAT()

    set @q = concat(q,' AND ALIAS_SECTION_ID = ',section_id);
                    ^
    
  3. 由于您的IN参数定义为VARCHAR您在构建查询时更好地引用它们的值

话虽如此,您的 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 ;
于 2013-08-28T06:24:52.147 回答