我有以下内容效果很好:
SET @param = '%string%';
SELECT *
FROM tbl
WHERE IF(@param IS NOT NULL, LIKE @param, TRUE);
但是,当我改为:
DELIMITER //
CREATE PROCEDURE test(IN param VARCHAR(255))
BEGIN
SET @param = param;
SELECT *
FROM tbl
WHERE IF(@param IS NOT NULL, LIKE @param, TRUE);
END //
DELIMITER ;
CALL test('%string%');
返回所有行,就好像没有传入参数一样。
我认为MySQL缺少一些限制或限制吗?
答案 0 :(得分:0)
不确定,但请使用准备好的声明
试试DELIMITER //
CREATE PROCEDURE test(IN param VARCHAR(255))
BEGIN
SET @param = param;
SET @q = CONCAT("SELECT *
FROM tbl
WHERE IF(",@param," IS NOT NULL, LIKE ",@param,", TRUE)");
PREPARE stmt FROM @q;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END //
DELIMITER ;
答案 1 :(得分:0)
此语句在语法上是错误的,不会被编译:
WHERE IF(@param IS NOT NULL, LIKE @param, TRUE);
并且您不能只放置这样的变量值来构造SQL语句 您需要准备好的声明来准备和执行此类声明。
请尝试以下操作:(您需要使用表中的有效列名替换column_name
。
DELIMITER //
DROP PROCEDURE IF EXISTS test //
CREATE PROCEDURE test( IN param VARCHAR( 255 ) )
BEGIN
SET @param = param;
SET @query = CONCAT( 'SELECT * FROM tbl WHERE column_name LIKE ' );
SET @query = CONCAT( @query, ' IF( \'', @param, '\' IS NOT NULL, \'' );
SET @query = CONCAT( @query, @param, '\', TRUE )' );
PREPARE stmt FROM @query;
EXECUTE stmt;
DROP PREPARE stmt; -- deallocate prepare stmt;
END;
//
DELIMITER ;
CALL test('%string%');
如果您运行select @query
,它将返回以下声明:
SELECT * FROM tbl
WHERE column_name LIKE IF( '%string%' IS NOT NULL, '%string%', TRUE )