您可以从如下所示的存储过程中获得灵感。更改实现所需解决方案所需的一切,包括所有相关限制和验证非常重要。
/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$
DROP PROCEDURE IF EXISTS `sp_check`$$
CREATE PROCEDURE `sp_check`(`p_table_schema` VARCHAR(64), `p_table_name` VARCHAR(64), `p_column_name` VARCHAR(64), `p_value` INT)
BEGIN
IF EXISTS (SELECT NULL
FROM `information_schema`.`columns`
WHERE `table_schema` = `p_table_schema` AND
`table_name` = `p_table_name` AND
`column_name` = `p_column_name`) THEN
SET @qry := CONCAT('SELECT IF(COUNT(`', `p_column_name`, '`), 1, 0) AS `EXISTS` FROM `', `p_table_schema`, '`.`', `p_table_name`, '` WHERE `', `p_column_name`, '` = ', `p_value`);
PREPARE stmt FROM @qry;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
ELSE
SELECT 0 AS `EXISTS`;
END IF;
END$$
DELIMITER ;
CALL `sp_check`('database1', 'table1', 'clmn_id_fk', 2218);