Skip to content

存储 Procedure

一句话解释

存储 procedure 是 named 块的 SQL code 存储 in 数据库那个能 是 called 使用参数.

用大白话说

A stored procedure is a named set of SQL statements saved in the database. You call it by name, optionally passing parameters, and it runs on the database server.

Stored procedures are useful for:

  • Encapsulating business logic: keep complex operations in one place on the server.
  • Reducing network traffic: instead of sending many queries from the app, call one procedure.
  • Security: grant execute permission on a procedure without granting direct table access.

The downside is that logic stored in the database is harder to version control, test, and debug than application code. Many modern applications prefer to keep logic in the app layer and use the database only for storage.

示例

sql
CREATE PROCEDURE transfer_funds(
  from_id INTEGER, to_id INTEGER, amount NUMERIC
) AS $$
BEGIN
  UPDATE accounts SET balance = balance - amount WHERE id = from_id;
  UPDATE accounts SET balance = balance + amount WHERE id = to_id;
END;
$$ LANGUAGE plpgsql;

-- Call it
CALL transfer_funds(1, 2, 100);

procedure encapsulates fund transfer as 单个 callable 操作.

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表