So I have this stored procedure which checks to see if a foreign key exists and if not, creates it. I need to run it in a script about 600+ times. At the end it should display the sum of skips, successes, and failures. I can't figure out how to count successes/failures from the prepared statement.
I tried storing EXECUTE stmt; to a var and also wrapping it with an IF/ELSE/END IF but no luck. The ALTER TABLE doesn't have to be a prepared statement if that helps.
DELIMITER //
DROP PROCEDURE IF EXISTS `add_constraint_if_not_exists`//
SET @skippedCount = 0;
SET @successCount = 0;
SET @failCount = 0;
CREATE PROCEDURE add_constraint_if_not_exists (sourceDB varchar(64), sourceTable varchar(64), sourceColumn varchar(64), constraintName varchar(64), targetDB varchar(64), targetTable varchar(64), targetColumn varchar(64))
BEGIN
IF EXISTS (
SELECT *
FROM information_schema.table_constraints
WHERE
table_schema = sourceDB
AND table_name = sourceTable
AND constraint_name = constraintName
AND constraint_type = 'FOREIGN KEY'
LIMIT 1
) THEN
SET @skippedCount = @skippedCount + 1;
ELSE
SET @sql = CONCAT('ALTER TABLE `',sourceDB,'`.`',sourceTable,'` ADD CONSTRAINT ',constraintName,' FOREIGN KEY (`',sourceColumn,'`) REFERENCES `', targetDB,'`.`',targetTable, '` (`',targetColumn,'`)');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
/*
IF @result = -1 THEN
#SELECT @result;
SET @failCount = @failCount + 1;
ELSE
SET @successCount = @successCount + 1;
END IF
*/
END IF;
END //
DELIMITER ;
/*
ALTER TABLE `source_db`.`source_table`
ADD CONSTRAINT `fk`
FOREIGN KEY (`source_column`)
REFERENCES `target_db`.`target_table` (`target_column`);
*/
CALL add_constraint_if_not_exists ('source_db', 'source_table', 'source_column', 'fk', 'target_db', 'target_table', 'target_column');
SELECT @skippedCount,@successCount,@failCount;