PostgreSQL - 如何执行“独立”代码?

时间:2011-04-05 18:36:45

标签: database postgresql codeblocks plpgsql

我已经习惯了SQL Server中的查询编辑器,可以自由编写&执行T-SQL。如何在PostgreSQL中执行以下代码而无需从中创建函数?

DECLARE 
    l integer = 1;
BEGIN
    CREATE TABLE product_i (id bigint, key integer, value integer);
    CREATE INDEX ix_product_i_size ON product_i(value) WHERE key = 1;
    CREATE INDEX ix_product_i_mass ON product_i(value) WHERE key = 2;

    LOOP
        BEGIN;
        INSERT
        INTO    product_i (id, key, value)
        SELECT  id, 1, CEILING(10 + RANDOM() * 90)
        FROM    generate_series(l, 1000) id;

        INSERT
        INTO    product_i (id, key, value)
        SELECT  id, 2, CEILING(10 + RANDOM() * 90)
        FROM    generate_series(l, 1000) id;

        COMMIT;
        l := l + 1000;
        EXIT WHEN l > 5000;
    END LOOP;
END

1 个答案:

答案 0 :(得分:4)

如果您至少使用PostgreSQL 9.0,则可以将其包含在DO块中:

http://www.postgresql.org/docs/9.0/static/sql-do.html