我正在尝试创建一个从表中返回值的函数
CREATE DEFINER = `root`@`localhost` FUNCTION `GETINFO` (
`INFO_ID` BIGINT( 20 ) ,
`ENTITY` VARCHAR( 255 ) ,
`ANCHOR` VARCHAR( 255 )
) RETURNS DOUBLE DETERMINISTIC READS SQL DATA SQL SECURITY DEFINER BEGIN DECLARE var_name DOUBLE;
# default value
SET var_name = -999.999;
# get desired value in database
SELECT MAX(`value`)
INTO var_name
FROM `mydata`
WHERE `info` = INFO_ID
AND `entity` = ENTITY
AND `anchor` = ANCHOR
LIMIT 0 , 1;
RETURN var_name;
END
当我尝试调用该函数时:
case 1) SELECT GETINFO(2, "134604843861826", "uniq") <========= real parameters, works fine
case 2) SELECT GETINFO(2, "1346048438618", "uniq") <========= just removed some chars to force error, but returns same value as case 1
case 3) SELECT GETINFO(12312, "123", "1233") <========= all params incorrect, now it returns NULL as expected
在案例2中问题,为什么它不尊重WHERE子句并返回NULL?
答案 0 :(得分:3)
问题是这些问题:
AND `entity` = ENTITY
AND `anchor` = ANCHOR
这些在过滤方面做 nothing ,因为它们都引用了表中的列。您应该始终在函数中为参数添加前缀以避免此问题。
CREATE DEFINER = `root`@`localhost` FUNCTION `GETINFO` (
`param_INFO_ID` BIGINT( 20 ) ,
`param_ENTITY` VARCHAR( 255 ) ,
`param_ANCHOR` VARCHAR( 255 )
) RETURNS DOUBLE DETERMINISTIC READS SQL DATA SQL SECURITY DEFINER BEGIN DECLARE var_name DOUBLE;
# default value
SET var_name = -999.999;
# get desired value in database
SELECT MAX(`value`)
INTO var_name
FROM `mydata`
WHERE `info` = param_INFO_ID
AND `entity` = param_ENTITY
AND `anchor` = param_ANCHOR
LIMIT 0 , 1;
RETURN var_name;
END