Postgresql 中文操作指南

DO

DO——执行匿名的代码块

DO — execute an anonymous code block

Synopsis

DO [ LANGUAGE lang_name ] code

Description

DO 执行匿名的代码块,或者换句话说,执行某个过程语言中的瞬态匿名函数。

DO executes an anonymous code block, or in other words a transient anonymous function in a procedural language.

代码块被视为没有参数的功能主体,返回 void 。它被解析并执行一次。

The code block is treated as though it were the body of a function with no parameters, returning void. It is parsed and executed a single time.

可选的 LANGUAGE 子句可以写在代码块之前或之后。

The optional LANGUAGE clause can be written either before or after the code block.

Parameters

  • code

    • The procedural language code to be executed. This must be specified as a string literal, just as in CREATE FUNCTION. Use of a dollar-quoted literal is recommended.

  • lang_name

    • The name of the procedural language the code is written in. If omitted, the default is plpgsql.

Notes

在经过 CREATE EXTENSION 的方式安装到当前数据库中后,待使用的过程语言才已完成安装。 plpgsql 已安装作为默认语言,但其他语言并未安装。

The procedural language to be used must already have been installed into the current database by means of CREATE EXTENSION. plpgsql is installed by default, but other languages are not.

该用户必须针对过程语言拥有 USAGE 权限,否则必须是超级用户(如果该语言不可信)。这是与用该语言创建函数相同的权限要求。

The user must have USAGE privilege for the procedural language, or must be a superuser if the language is untrusted. This is the same privilege requirement as for creating a function in the language.

如果 DO 在事务块中执行,则该过程代码无法执行事务控制语句。仅当 DO 在其自身的事务中执行时才允许使用事务控制语句。

If DO is executed in a transaction block, then the procedure code cannot execute transaction control statements. Transaction control statements are only allowed if DO is executed in its own transaction.

Examples

授予角色 webuser 对架构 public 中所有视图的所有权限:

Grant all privileges on all views in schema public to role webuser:

DO $$DECLARE r record;
BEGIN
    FOR r IN SELECT table_schema, table_name FROM information_schema.tables
             WHERE table_type = 'VIEW' AND table_schema = 'public'
    LOOP
        EXECUTE 'GRANT ALL ON ' || quote_ident(r.table_schema) || '.' || quote_ident(r.table_name) || ' TO webuser';
    END LOOP;
END$$;

Compatibility

SQL 标准中没有 DO 语句。

There is no DO statement in the SQL standard.