如何在php中编写mysql用户自定义函数

时间:2015-03-27 11:19:26

标签: php mysql user-defined-functions

请告诉我如何在PHP中定义MySQL用户自定义函数...

我使用以下代码。但它无效。

它抛出错误:

  

" (1313)RETURN仅允许在FUNCTION"

中使用
$mysqli = new mysqli( $DBHost, $DBUserName, $DBPassword, $DBName );


$Query =
"CREATE PROCEDURE FunGetRegistryValue(OUT Param_RegistryKey varchar(40))
BEGIN
    DECLARE vResult varchar(90);
    SELECT  iFnull(Value,'') INTO vResult FROM Project_Registry Where RegistryKey=Param_RegistryKey;
    RETURN(vResult);
END;";

if( !$mysqli->query( $Query ) ) {
    echo "Stored procedure creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}

当我使用FUNCTION关键字而不是PROCEDURE时,我得到语法错误...

请为我提供" VALUE RETURNING FUNCTION"

的示例代码

2 个答案:

答案 0 :(得分:0)

DELIMITER $$ 
CREATE DEFINER=root@localhost
FUNCTION FunGetRegistryValue(Param_RegistryKey varchar(40)) 
RETURNS varchar(90) 
CHARSET latin1 DETERMINISTIC 
BEGIN 
    DECLARE vResult varchar(90); 
    SELECT iFnull(Value,'') INTO vResult 
    FROM Project_Registry Where RegistryKey=Param_RegistryKey;
    RETURN(vResult); 
END$$ 
DELIMITER ;

最初由Fozia发表评论。我把它添加为答案,这样它就不会在查询上乱七八糟地运行并且清晰易读。

答案 1 :(得分:-1)

$ mysqli = new mysqli($ DBHost,$ DBUserName,$ DBPassword,$ DBName);

$Query =
"DROP FUNCTION IF EXISTS FunGetRegistryValue;

CREATE   FUNCTION FunGetRegistryValue(Param_RegistryKey VARCHAR(40)) RETURNS VARCHAR(90) CHARSET latin1
   DETERMINISTIC
BEGIN
   DECLARE vResult VARCHAR(90);
   SELECT  IFNULL(VALUE,'') INTO vResult FROM Project_Registry WHERE RegistryKey=Param_RegistryKey;
   RETURN(vResult);
   END;";

if( !$mysqli->multi_query( $Query ) ) {
    echo $mysqli->error;
    exit();
}