Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

ส่งคืนตารางจากฟังก์ชัน MySQL ได้หรือไม่

ไม่สามารถส่งคืนตารางจากฟังก์ชัน (FUNCTION) ของ MySQL ได้ ฟังก์ชันสามารถส่งคืนได้แค่ string, integer, char ฯลต หากต้องการส่งคืนชุดข้อมูล (result set) ให้ใช้ Stored Procedure แทน

สร้างตารางตัวอย่าง

mysql> create table DemoTable696 (
    Id int,
    Name varchar(100)
);
Query OK, 0 rows affected (0.77 sec)

เพิ่มข้อมูลตัวอย่าง

mysql> insert into DemoTable696 values(100, 'Mike');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable696 values(101, 'Sam');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable696 values(102, 'Adam');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable696 values(103, 'Carol');
Query OK, 1 row affected (0.20 sec)

แสดงข้อมูลทั้งหมด

mysql> select * from DemoTable696;

ผลลัพธ์

+------+-------+
| Id   | Name  |
+------+-------+
| 100  | Mike  |
| 101  | Sam   |
| 102  | Adam  |
| 103  | Carol |
+------+-------+
4 rows in set (0.00 sec)

Stored Procedure ส่งคืนชุดข้อมูล (Result Set)

mysql> DELIMITER //
mysql> CREATE PROCEDURE getResultSet(studId int)
    BEGIN
        select * from DemoTable696 where Id = studId;
    END
    //
Query OK, 0 rows affected (0.14 sec)
mysql> DELIMITER ;

เรียก Stored Procedure

mysql> call getResultSet(103);

ผลลัพธ์

+------+-------+
| Id   | Name  |
+------+-------+
| 103  | Carol |
+------+-------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.01 sec)

สรุป: FUNCTION ส่งคืนค่าเดี่ยว (scalar) แต่ STORED PROCEDURE สามารถส่งคืน result set (หลายแถว หลายคอลัมน์) ได้