简体   繁体   English

MySQL存储过程

[英]MySQL Stored Procedures

I have a few questions regarding stored procedures. 关于存储过程,我有几个问题。 After hours of googling, I really can't find any really simple query examples. 经过数小时的谷歌搜索,我真的找不到任何非常简单的查询示例。

CREATE PROCEDURE test1(IN uid INT)
BEGIN
    SELECT USER_NAME FROM USERS WHERE USER_ID = uid;
END //

this query takes 'uid' as input and selects the username for that uid, Can someone please explain how I call that procedure in php and also, how do I output the actual rows to the php var? 此查询以“ uid”作为输入并选择该uid的用户名。有人可以解释一下我如何在php中调用该过程,以及如何将实际行输出到php var?

AFAIK you just need to put call before it in the query: AFAIK您只需要在查询中放置呼叫:

$result = mysql_query("CALL test1(".$args.")");
$username = mysql_result($result);

You should consider doing this with a stored function that returns a single VARCHAR: 您应该考虑使用返回单个VARCHAR的存储函数来执行此操作:

CREATE FUNCTION test1(uid INT) RETURNS VARCHAR(100)
BEGIN
    DECLARE V_RETURN_VAL VARCHAR(100);

    SELECT USER_NAME 
    INTO V_RETURN_VAL
    FROM USERS 
    WHERE USER_ID = uid;

    RETURN V_RETURN_VAL;
END //

You can just use "CALL" and retrieve the rows as if it were a normal query. 您可以仅使用“ CALL”并像正常查询一样检索行。

The only case where it is different is if the procedure returns multiple result sets, in which case you MUST go through them all (even empty ones) with a method which gives the next result set. 唯一不同的情况是该过程返回多个结果集,在这种情况下,您必须使用给出下一个结果集的方法遍历所有结果集(甚至是空的)。

OUT parameters are a waste of time as they require more round-trips and server-side state to fetch their results; OUT参数浪费时间,因为它们需要更多的往返次数和服务器端状态才能获取结果。 you invariably write more code and have more bugs if you use them. 如果使用它们,您总是会编写更多的代码,并且会有更多的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM