Computer >> Máy Tính >  >> Lập trình >> MySQL

Chèn dữ liệu vào một bảng trong thủ tục lưu trữ MySQL?

Để chèn vào một bảng trong thủ tục được lưu trữ, cú pháp như sau -

create procedure yourProcedureName(OptionalParameter)
   begin
   insert into yourTableName() values(yourValue1,yourValue2,...N);
end

Để hiểu cú pháp trên, trước tiên chúng ta hãy tạo một bảng -

mysql> create table DemoTable1928
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Name varchar(20),
   Age int
   );
Query OK, 0 rows affected (0.00 sec)

Đây là truy vấn để tạo một thủ tục được lưu trữ -

mysql> delimiter //
mysql> create procedure insert_demo(IN Name varchar(40),IN Age int)
   begin
   insert into DemoTable1928(Name,Age) values(Name,Age);
   end
   //
Query OK, 0 rows affected (0.00 sec)
mysql> delimiter ;

Bây giờ bạn có thể gọi một thủ tục đã lưu trữ bằng lệnh CALL -

mysql> call insert_demo('Chris',24);
Query OK, 1 row affected, 1 warning (0.00 sec)

Hiển thị tất cả các bản ghi từ bảng bằng câu lệnh select -

mysql> select * from DemoTable1928;

Điều này sẽ tạo ra kết quả sau -

+----+-------+------+
| Id | Name  |  Age |
+----+-------+------+
|  1 | Chris |   24 |
+----+-------+------+
1 row in set (0.00 sec)