实现说明
核心是一条 CREATE 语句,作用于 n。
常见问题
这段 SQL 涉及哪些关系?
引用的是 n。
核心语句
DO $$
DECLARE
target_table text := 'user''s orders';
status text := 'it''s active';
n bigint;
BEGIN
EXECUTE format('SELECT count(*) FROM %I WHERE status = %L',
target_table, status)
INTO n;
RAISE NOTICE 'matching rows: %', n;
END $$;
INSERT INTO "user's orders" VALUES (1, 'it''s active'), (2, 'it''s active');
CREATE TABLE "user's orders" (id int, status text);
代码示例
-- 服务端拼动态语句(plpgsql EXECUTE)时,标识符与字面量必须分开引用:
-- %I = quote_ident:给标识符加引号、双写内部双引号
-- %L = quote_literal:给字面量加引号、转义内部单引号
CREATE TABLE "user's orders" (id int, status text);
INSERT INTO "user's orders" VALUES (1, 'it''s active'), (2, 'it''s active');
DO $$
DECLARE
target_table text := 'user''s orders';
status text := 'it''s active';
n bigint;
BEGIN
EXECUTE format('SELECT count(*) FROM %I WHERE status = %L',
target_table, status)
INTO n;
RAISE NOTICE 'matching rows: %', n;
END $$;
-- 对照:裸拼接在 ' 处把字符串提前终结 → 语法错误,也是注入入口
-- EXECUTE 'SELECT count(*) FROM ' || target_table
-- || ' WHERE status = ''' || status || '''';