您可以在语句中使用一个变量,然后再使用它:
SELECT count(*) FROM my_table WHERE field1='xxx' into @rowCount
Walter A编辑:
在进行了一些额外的更改后,这项功能发挥了作用。
我的最终解决方案看起来像
DROP PROCEDURE IF EXISTS myDatabase.checkSQLCount;
CREATE PROCEDURE myDatabase.checkSQLCount(IN countQuery VARCHAR(1000), IN minCount INT, IN maxCount INT)
BEGIN
DECLARE success INT;
DECLARE rowCount INT;
SELECT countQuery AS '=== SQL statement ===';
SET @stmt = CONCAT(countQuery, ' INTO @rowCount');
PREPARE stmt FROM @stmt;
EXECUTE stmt ;
DEALLOCATE PREPARE stmt;
-- If the matched rows are outside the specified range, set the success flag to 0
IF @rowCount < minCount OR @rowCount > maxCount THEN
SELECT CONCAT('ERROR: ', @rowCount, ' not between ', minCount, ' and ', maxCount)
AS 'Check expected nr matched rows';
SET success := 0;
ELSE
SELECT CONCAT('OK: ', @rowCount, ' is between ', minCount, ' and ', maxCount)
AS 'Check expected nr matched rows';
SET success := 1;
END IF;
-- Insert the result into the CallResults table
INSERT INTO myDatabase.CallResults (success) VALUES (success);
END //
通过此过程,以及
handleCallResults
在这个问题上,我可以写
-- Start transaction
START TRANSACTION;
-- Create a temporary table to store the results of each SQL call, always needed
CREATE TEMPORARY TABLE IF NOT EXISTS bahman.CallResults (success INT);
CALL myDatabase.checkAffectedRows(
"UPDATE myDatabase.myTable SET currency='xxx' WHERE id < 100",
1,100);
CALL myDatabase.checkSQLCount(
"SELECT count(*) FROM myDatabase.myTable WHERE currency='yyy'",
30, 35);
-- Handle the results and decide whether to commit or rollback the transaction
CALL myDatabase.handleCallResults();