How to declare local variables in postgresql?

后端 未结 1 2042
一个人的身影
一个人的身影 2020-12-14 14:31

There is an almost identical, but not really answered question here.

I am migrating an application from MS SQL Server to PostgreSQL. In many places in code I use loc

相关标签:
1条回答
  • 2020-12-14 15:05

    Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.

    In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:

    CREATE OR REPLACE FUNCTION somefuncname() RETURNS int LANGUAGE plpgsql AS $$
    DECLARE
      one int;
      two int;
    BEGIN
      one := 1;
      two := 2;
      RETURN one + two;
    END
    $$;
    SELECT somefuncname();
    

    The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.

    0 讨论(0)
提交回复
热议问题