SQL Stored Procedures là một tập hợp các câu lệnh SQL được lưu trữ trong cơ sở dữ liệu và có thể được gọi lại nhiều lần.
Cú pháp tạo Stored Procedure:
CREATE [PROCEDURE | PROC] [schema_name.]procedure_name ( [parameter1_name data_type], [parameter2_name data_type], ... ) [AS] BEGIN -- Các câu lệnh SQL END
Giải thích:
- CREATE PROCEDURE | PROC: Từ khóa để tạo Stored Procedure.
- schema_name: Tên schema (tùy chọn).
- procedure_name: Tên Stored Procedure.
- parameter_name: Tên tham số.
- data_type: Kiểu dữ liệu của tham số.
- AS: Từ khóa bắt đầu phần thân Stored Procedure.
- BEGIN: Bắt đầu phần thân Stored Procedure.
- — Các câu lệnh SQL: Các câu lệnh SQL được thực thi khi Stored Procedure được gọi.
- END: Kết thúc phần thân Stored Procedure.
Ví dụ:
CREATE PROCEDURE GetCustomerOrders ( @CustomerID int ) AS BEGIN SELECT * FROM Orders WHERE CustomerID = @CustomerID; END
Cách gọi Stored Procedure:
EXEC [schema_name.]procedure_name [@parameter1_value, @parameter2_value, ...];
Ví dụ:
EXEC GetCustomerOrders 10;
Lưu ý:
- Stored Procedure có thể giúp bạn:
- Tái sử dụng các tập hợp câu lệnh SQL.
- Giảm thiểu mã SQL.
- Nâng cao hiệu suất truy vấn.
- Tăng tính bảo mật cho dữ liệu.
- Bạn có thể sử dụng các tham số để truyền dữ liệu vào Stored Procedure.
- Stored Procedure có thể trả về dữ liệu bằng cách sử dụng SELECT hoặc OUTPUT.
Xem thêm:
- Q80 Which three instance situations are possible with the Oracle Database server without multitenant?
- Trí tuệ nhân tạo và an ninh mạng: Đối đầu với hacker bằng AI
- Cách thực hiện checkpoint trong PostgreSQL
- Q160 Examine the description of the BOOKS_TRANSACTIONS table
- Q3. Examine these queries and their output After a system crash, an instance restart and an attempted opening of the PDBs result in