Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Dùng IN() để lấy bản ghi cụ thể trong stored procedure MySQL


Tạo bảng:

mysql> create table DemoTable2004 ( UserId varchar(20), UserName varchar(20) ); Query OK, 0 rows affected (0.57 sec)

Thêm dữ liệu:

mysql> insert into DemoTable2004 values('John_123','John'); Query OK, 1 row affected (0.93 sec)
mysql> insert into DemoTable2004 values('23456_Carol','Carol'); Query OK, 1 row affected (0.25 sec)
mysql> insert into DemoTable2004 values('111_Bob','Bob'); Query OK, 1 row affected (0.14 sec)

Hiển thị dữ liệu:

mysql> select * from DemoTable2004;
+-------------+----------+
| UserId      | UserName |
+-------------+----------+
| John_123    | John     |
| 23456_Carol | Carol    |
| 111_Bob     | Bob      |
+-------------+----------+
3 rows in set (0.00 sec)

Tạo stored procedure nhận tham số uId, dùng IN() để lọc:

mysql> delimiter //
mysql> create procedure test_of_in(IN uId varchar(20))
    BEGIN
        select * from DemoTable2004 where UserId IN(uId);
    END
//
Query OK, 0 rows affected (0.15 sec)
mysql> delimiter ;

Gọi procedure:

mysql> call test_of_in('23456_Carol');

Kết quả:

+-------------+----------+
| UserId      | UserName |
+-------------+----------+
| 23456_Carol | Carol    |
+-------------+----------+
1 row in set (0.00 sec)