简体   繁体   中英

MySQL Stored Procedures Returning Select

This is a very basic MySQL question but I could not find an answer. Suppose the following storedprocedure body;

DECLARE Existing INT DEFAULT 0;
SELECT SQL_CALC_FOUND_ROWS name FROM users WHERE id = pid LIMIT 1;
SELECT FOUND_ROWS() INTO Existing;
Select Existing;

when I run it it always returns the first SELECT results. However I expect it to return the last (SELECT Existing) results. Is this behaviour normal? If so, how can I change it, because first select is just for checking and the last one is what I need.

(The real logic is different from this, I just simplified it here)

You could do something like this instead:

SELECT COALESCE(id/id, 0) AS Existing
    FROM users 
    WHERE id = pid 
    LIMIT 1;

If id is found, you'll return a 1 (id/id = 1). If id is not found, you'll return a 0 (id/id IS NULL and the COALESCE will return the 0).

The problem is the MySQL "client" that you are using to run the stored procedure. The stored procedure will return the result set of all queries but the client should support it. Are you running your queries in phpMyAdmin or another similar client? Try calling the stored procedure using the default client - the command prompt and you will see that it returns results from all queries. Please read last para on this page .

Now that was for some pointers. Now coming to how you can return values from the procedure. You can do this using the OUT parameter that is used to pass a value from the procedure back to the caller. Please read more on this page on the MySQL website - the example on that page explains this.

Hope this helps!

just for debugging, if two select sql return column count are equal, you could use union:

select 1, '100' union select '3434', 2;

You could create table variables, fill it, then select from it

CREATE PROCEDURE my_proc () BEGIN 

CREATE TEMPORARY TABLE TempTable (myid int, myfield varchar(100)); 
INSERT INTO TmpTable SELECT tblid, tblfield FROM Table1; 

SELECT * FROM TEMPORARY;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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