CREATE PROCEDURE proc_IF (IN param1 INT)
BEGIN
SET @query = CONCAT('SELECT * FROM articles ', IF(param1 = 0, " WHERE NAME = 'Тест';", , " WHERE NAME = 'Проверка';");
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
SET @query = 'SELECT * FROM articles ';
IF variable1 = 0 THEN
@query = CONCAT(@query, ' WHERE name = 'Тест'')
END IF;
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
CREATE PROCEDURE proc_IF (IN param1 INT, IN param2 VARCHAR(255))
BEGIN
SET @search_name = param2;
SET @query = 'SELECT * FROM articles ';
IF param1 = 0 THEN
@query = CONCAT(@query, ' WHERE name = ?')
END IF;
PREPARE stmt FROM @query;
EXECUTE stmt USING @search_name;
DEALLOCATE PREPARE stmt;
END
Slava Rozhnev, Только почему то это не работает, указывает ошибку синтаксиса в строке с CONCAT
CREATE PROCEDURE proc_IF (IN param1 INT)
BEGIN
SET @query = CONCAT('SELECT * FROM articles');
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
CREATE PROCEDURE getCountry(IN `locale` char(2))
BEGIN
SET @sql = 'SELECT * FROM articles';
PREPARE getCountrySql FROM @sql;
EXECUTE getCountrySql;
DEALLOCATE PREPARE getCountrySql;
END
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 3
На эту строку SET @sql
DELIMITER $$
DROP PROCEDURE IF EXISTS `article_search`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `article_search`(IN search VARCHAR(255))
BEGIN
SET @search = search;
SET @query = 'SELECT * FROM articles ';
IF search <> '' THEN
SET @query = CONCAT(@query, ' WHERE name = ? ');
END IF;
PREPARE stmt FROM @query;
IF search <> '' THEN
EXECUTE stmt USING @search;
ELSE
EXECUTE stmt;
END IF;
DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;