← 中文资源

简体中文版本

SET LOCAL 语句超时护栏

SET LOCAL statement_timeout 只管当前事务内的语句:超时报 canceling statement due to statement timeout,事务结束后连接自动回到默认值。

阅读英文原文

实现说明

实际执行的是 SELECT——涉及的对象是 sales。 真正干活的子句:用 SUM 做聚合;GROUP BY 把同组行折叠成每个分组一行。

常见问题

这段 SQL 涉及哪些关系?

sales——这些对象以名字直接进入查询,无需连接。

核心语句

SELECT region, SUM(revenue) AS revenue
FROM sales
GROUP BY region;
SET LOCAL statement_timeout = '2s';
SET statement_timeout = '30s';

代码示例

BEGIN;
-- SET LOCAL applies only inside the current transaction: cap reporting queries with a timeout
SET LOCAL statement_timeout = '2s';

SELECT region, SUM(revenue) AS revenue
FROM sales
GROUP BY region;

-- A timed-out statement receives: ERROR: canceling statement due to statement timeout
-- The transaction is then aborted; the app should ROLLBACK and retry or degrade
ROLLBACK;

-- Contrast: session-level SET affects every later statement on the connection and must be reset by hand
SET statement_timeout = '30s';
RESET statement_timeout;