0

Calling a stored procedure using input and output parameters returns different results compared to running the stored procedure code directly as a query. I cannot grasp why MySQL 8 would process the stored procedure like this. Would appreciate it of someone could explain this behavior and the reason behind it.

MySQL version: GPL version 8.0.18

Reconstructed code

DELIMITER $$
USE `temp`$$

CREATE TABLE `TestTable` (
  `id1` smallint(5) unsigned NOT NULL,
  `id2` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `text1` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '',
  `text2` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '0',
  UNIQUE KEY `uq_TestTable_id1_id2` (`id1`,`id2`),
  KEY `ix_TestTable_id1_id2` (`id1`,`id2`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci$$

CREATE PROCEDURE `proc_test`(
    IN id1 smallint unsigned,
    IN id2 nvarchar(10),
    OUT outtext1 nvarchar(20),
    OUT outtext2 nvarchar(10)
    )
BEGIN

    SET outtext1 = '';
    SET outtext2 = '';

    SELECT
        `text1`, `text2`
        INTO outtext1, outtext2
    FROM  `TestTable`
    WHERE
        `id1` = id1 AND 
        `id2` = id2
    LIMIT 1;

END$$

INSERT INTO `TestTable`
(`id1`, `id2`, `text1`, `text2`)
VALUES
(1, 'id2', 'text1', 'text2')$$

DELIMITER ;

-- Returns text1 and text2 values
call proc_test(1, 'id2', @outtext1, @outtext2);
select @outtext1, @outtext2;

-- Should return nothing but returns text1 and text2 values while there is no id2 with a value of xxx
call proc_test(1, 'xxx', @outtext1, @outtext2);
select @outtext1, @outtext2;

-- Should return nothing but returns text1 and text2 values while there is no id1 with a value of 9
call proc_test(9, 'id2', @outtext1, @outtext2);
select @outtext1, @outtext2;

-- Run normal query: Result text1 and text2 as expected
SELECT `text1`, `text2`
FROM  `TestTable`
WHERE `id1` = 1 AND `id2` = 'id2';

-- Run normal query: Result is empty as expected
SELECT `text1`, `text2`
FROM  `TestTable`
WHERE `id1` = 1 AND `id2` = 'xxx';

-- Run normal query: Result is empty as expected
SELECT `text1`, `text2`
FROM  `TestTable`
WHERE `id1` = 9 AND `id2` = 'id2';

-- Cleanup
DROP PROCEDURE `proc_test`;
DROP TABLE `testtable`;

  • Your procedure inputs have the same names as your columns so MySQL is treading `\`id1\` = id1` as both being the column `id1`; hence the condition is always true. Just change the input names e.g. https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=2477db4c1bb83e4f3ff4f2ad94d92278 – Nick Feb 19 '20 at 07:16
  • Thank you Nick. That is correct. The input parameter and the column name can't be the same. – Mc van Staaden Feb 19 '20 at 07:24

0 Answers0