如何redeclare/redefine MySQL User Function 每次刷新?

How to redeclare/redefine MySQL User Function every time you refresh?

是否可以在每次刷新时重新声明一个MySQL函数,这是我的代码

mysql_query("
DROP FUNCTION IF EXISTS Add_num;
CREATE FUNCTION Add_num(LAT_A INT)
RETURNS INT
READS SQL DATA
DETERMINISTIC
BEGIN
DECLARE Ans BIGINT;
SET Ans = LAT_A + 2;
RETURN Ans;
END");

即使我有 DROP FUNCTION IF EXISTS Add2; 行,刷新时功能保持不变。例如,我在 SET Ans = LAT_A + 2; 行中将 2 更改为 3 然后刷新,它仍然添加 2 而不是 3.

我已经为您编写了解决方案,但在这里我使用了 mysqli,因为您会知道 mysql_query() 不接受分号 (;) 并且一次只能执行一个查询。

代码如下:

$mysqli = new mysqli("localhost", "root", "", "test");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if (!$mysqli->query("DROP FUNCTION IF EXISTS Add_num") ||
    !$mysqli->query("CREATE FUNCTION Add_num(LAT_A INT) RETURNS INT  READS SQL DATA  DETERMINISTIC  BEGIN  DECLARE Ans BIGINT;  SET Ans = LAT_A + 4;  RETURN Ans;  END;")) {
    echo "Function creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
$select_qry = " SELECT Add_num(6) as result";
$result = $mysqli->query($select_qry);

if ($result) {
    $row = $result->fetch_assoc();
    echo "Result is :{$row['result']}";
}

$mysqli->close();