首页 文章

PostgreSql - 声明整数变量

提问于
浏览
0

我试图在postgresql sql脚本中声明默认值为0的整数变量:

DECLARE user_id integer;

但它返回异常:

错误:语法错误处于或接近“整数”

我不知道如何声明变量然后在while循环中使用此变量 .

2 回答

  • 3

    您可以't use DECLARE in a SQL statement. What you want to do requires plpgsql. danielarend'的答案是对的,但您可能想要探索DO(https://www.postgresql.org/docs/current/static/sql-do.html),它可以让您编写adhoc plpgsql而无需定义函数 .

  • 2

    您必须将代码放在用户定义的函数中 . 它不适用于sql窗口 . 下面的示例是一个函数,它返回您发送的数字 . 变量

    --mybase is your database name. If public, remove it.
      CREATE OR REPLACE FUNCTION mybase.my_new_rotine(numeric)
      RETURNS numeric AS
      $BODY$
      --here, get the first variable from function
        declare id numeric= $1;
    
        begin
       --return the number
           return id;
        end;
      $BODY$
    
      LANGUAGE plpgsql VOLATILE
    

    那么,你可以在sql窗口上使用它,如下所示:

    select * from mybase.my_new_rotine(1)
    

    将返回1

相关问题