帶 SELECT 的 MySQL 儲存過程可以返回整個表


我們首先建立一個表 -

mysql> create table DemoTable1971
   (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentName varchar(20),
   StudentPassword int
   );
Query OK, 0 rows affected (0.00 sec)

使用 insert 命令向表中插入一些記錄 -

mysql> insert into DemoTable1971(StudentName,StudentPassword) values('John','123456');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1971(StudentName,StudentPassword) values('Chris','123456');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1971(StudentName,StudentPassword) values('David','123456');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1971(StudentName,StudentPassword) values('Mike','123456');
Query OK, 1 row affected (0.00 sec)

使用 select 語句顯示錶中的所有記錄 -

mysql> select * from DemoTable1971;

這將產生以下輸出 -

+-----------+-------------+-----------------+
| StudentId | StudentName | StudentPassword |
+-----------+-------------+-----------------+
|         1 | John        |          123456 |
|         2 | Chris       |          123456 |
|         3 | David       |          123456 |
|         4 | Mike        |          123456 |
+-----------+-------------+-----------------+
4 rows in set (0.00 sec)

以下是如何建立儲存過程的查詢 -

mysql> delimiter //
mysql> create procedure returnAll(pass varchar(30))
   begin
   select * from DemoTable1971 where StudentPassword=pass;
   end
   //
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;

現在,可以使用 CALL 命令呼叫儲存過程 -

mysql> call returnAll('123456');

這將產生以下輸出,顯示整個表 -

+-----------+-------------+-----------------+
| StudentId | StudentName | StudentPassword |
+-----------+-------------+-----------------+
|         1 | John        |          123456 |
|         2 | Chris       |          123456 |
|         3 | David       |          123456 |
|         4 | Mike        |          123456 |
+-----------+-------------+-----------------+
4 rows in set (0.00 sec)
Query OK, 0 rows affected, 1 warning (0.00 sec)

更新於:31-12-2019

3 千次 + 瀏覽

開始您的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.