Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return table from MySQL function

Tags:

mysql

CREATE FUNCTION myFunction(id INT) RETURNS TABLE  
BEGIN  
   RETURN SELECT * FROM board;  
END  

This query gives following error:

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'TABLE  
like image 371
Ankit Aranya Avatar asked May 02 '14 06:05

Ankit Aranya


People also ask

How can I return multiple values from a function in MySQL?

MySQL stored function returns only one value. To develop stored programs that return multiple values, you need to use stored procedures with INOUT or OUT parameters. If you are not familiar with INOUT or OUT parameters, check it out the stored procedure's parameters tutorial for the detailed information.

How do you call a function in MySQL?

A function can be called by specifying its name and parameter list wherever an expression of the appropriate data type may be used. To show how stored functions can be called, we'll use the simple stored function shown in Example 10-6.

How do I return a column in MySQL?

Use the asterisk character (*) in place of a column list in a SELECT statement to instruct MySQL to return every column from the specified table.


Video Answer


1 Answers

As per documentation on user defined functions in MySQL
you can only return values of type {STRING|INTEGER|REAL|DECIMAL}

CREATE [AGGREGATE] FUNCTION function_name RETURNS {STRING|INTEGER|REAL|DECIMAL}
    SONAME shared_library_name

If you want to read a select resultset you have to define a procedure but not function.

DELIMITER //

DROP PROCEDURE IF EXISTS myProcedure //

CREATE PROCEDURE 
  myProcedure( id INT )
BEGIN  
   SELECT * FROM board
     -- add where condition if required
    WHERE Col_name = id
   ;  
END 
//

DELIMITER ;

And you can call procedure like

call myProcedure( 6 )

That returns implicit objects based on the statements used in the procedure.

like image 110
Ravinder Reddy Avatar answered Sep 19 '22 21:09

Ravinder Reddy