將列值儲存到 MySQL 儲存過程的變數中


要宣告變數,請在 MySQL 儲存過程中使用 DECLARE。讓我們首先建立一個表 -

mysql> create table DemoTable2034
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(20),
   -> StudentAge int
   -> );
Query OK, 0 rows affected (0.49 sec)

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

mysql> insert into DemoTable2034(StudentName,StudentAge) values('Chris',23);
Query OK, 1 row affected (0.10 sec)

mysql> insert into DemoTable2034(StudentName,StudentAge) values('David',21);
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable2034(StudentName,StudentAge) values('Robert',25);
Query OK, 1 row affected (0.15 sec)

mysql> insert into DemoTable2034(StudentName,StudentAge) values('Mike',19);
Query OK, 1 row affected (0.14 sec)

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

mysql> select *from DemoTable2034;

將生成以下輸出 -

+-----------+-------------+------------+
| StudentId | StudentName | StudentAge |
+-----------+-------------+------------+
| 1         | Chris       | 23         |
| 2         | David       | 21         |
| 3         | Robert      | 25         |
| 4         | Mike        | 19         |
+-----------+-------------+------------+
4 rows in set (0.00 sec)

以下是要建立一個儲存過程並將上述表的列值儲存在儲存過程變數中的查詢 -

mysql> delimiter //
mysql> create procedure select_into_variable(id int)
   -> begin
   -> declare name varchar(50);
   -> select StudentName into name from DemoTable2034 where StudentId=id;
   -> select concat('Your Name is= ',name);
   -> end
   -> //
Query OK, 0 rows affected (0.09 sec)
mysql> delimiter ;

呼叫儲存過程 -

mysql> call select_into_variable(4);

將生成以下輸出 -

+-------------------------------+
| concat('Your Name is= ',name) |
+-------------------------------+
| Your Name is= Mike            |
+-------------------------------+
1 row in set (0.04 sec)
Query OK, 0 rows affected (0.06 sec)

更新於:2020 年 4 月 7 日

904 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.