How can I execute pl/pgsql code without creating a function?

前端 未结 3 381
南旧
南旧 2021-02-01 01:13

With SQL Server, I can execute code ad hoc T-SQL code with full procedural logic through SQL Server Management Studio, or any other client. I\'ve begun working with PostgreSQL a

3条回答
  •  一生所求
    2021-02-01 01:42

    I struggled to get this working because it's fairly strict about adding semi colons in exactly the right places. But once you get used to that it works well. Besides the inability to return records of course, however you can raise notices & exceptions and do the other workarounds like using temp tables as @ErwinBrandstetter pointed out in a comment above.

    e.g.:

    DO 
    $$
    BEGIN
      IF EXISTS(SELECT 'any rows?' 
                  FROM {your_table} 
                  WHERE {your_column} = 'blah')
      THEN
          RAISE NOTICE 'record exists';
      ELSE
          RAISE EXCEPTION 'record does not exist';
      END IF;
    
      DROP TABLE IF EXISTS foo;
    
      CREATE TEMP TABLE foo AS
      SELECT 'bar'::character varying(5) as baz;
    END 
    $$;
    
    SELECT * FROM foo;
    

提交回复
热议问题