PL / pgSQL函数声明中的语法错误

时间:2014-12-29 10:18:15

标签: postgresql plpgsql pgadmin procedures

任何人都可以帮我这个程序吗?这是一个非常简单的,只是想在表中插入一些数据,但是pgAdmin给了我一些错误。

这是程序代码:

CREATE OR REPLACE FUNCTION FILL_INVOICE2(IN_NUM integer)
RETURNS void AS
DECLARE
    counter numeric := 0;
    BEGIN
    IF in_num > 1 THEN

    WHILE counter < 10
    LOOP
        INSERT INTO INVOICE(ID,INVOICE_ID,SUBSCRIBER_ID,AMOUNT,INVOICE_DATE,RECORD_DATE,INVOICE_TYPE,REST_TO_PAY,DESCRIPTION,INVOICE_REFERENCE)
VALUES(counter,counter,counter,100,current_date,current_date,1,100,'Telco services',1111);

         counter := counter + 1;
         RAISE NOTICE 'The counter is %', counter;
    END LOOP;
    END IF;

    RETURN;

  END;

错误是:

ERROR:  syntax error at or near "DECLARE counter numeric"
LINE 3: DECLARE
        ^
********** Error **********

ERROR: syntax error at or near "DECLARE counter numeric"
SQL state: 42601
Character: 75"

2 个答案:

答案 0 :(得分:1)

正文应该作为字符串传递

CREATE OR REPLACE FUNCTION FILL_INVOICE2(IN_NUM integer) RETURNS void AS 
$$
DECLARE
    counter numeric := 0; 
BEGIN
   IF in_num > 1 THEN
     WHILE counter < 10 LOOP 
       INSERT INTOI NVOICE(ID,INVOICE_ID,SUBSCRIBER_ID,AMOUNT,INVOICE_DATE,
            RECORD_DATE,INVOICE_TYPE,REST_TO_PAY,DESCRIPTION,INVOICE_REFERENCE)
       VALUES(counter,counter,counter,100,current_date,current_date,1,100,
          'Telco services',1111);
       counter := counter + 1;
       RAISE NOTICE 'The counter is %', counter;

     END LOOP; 
   END IF;
   RETURN;
END;
$$

您可以使用$$标记多行字符串的开头。

答案 1 :(得分:1)

这样可行:

CREATE OR REPLACE FUNCTION fill_invoice2(in_num integer)
  RETURNS void AS
$func$
DECLARE
   counter numeric := 0;
BEGIN
   IF in_num > 1 THEN
      WHILE counter < 10
      LOOP
         INSERT INTO invoice(ID,INVOICE_ID,SUBSCRIBER_ID,AMOUNT,INVOICE_DATE,RECORD_DATE
                            ,INVOICE_TYPE,REST_TO_PAY,DESCRIPTION,INVOICE_REFERENCE)
         VALUES(counter,counter,counter,100,current_date,current_date
               ,1,100,'Telco services',1111);

         counter := counter + 1;
         RAISE NOTICE 'The counter is %', counter;
      END LOOP;
   END IF;
END
$func$ LANGUAGE plpgsql;

重点

但整个功能看起来不必要的昂贵 使用基于generate_series()的单个INSERT来替换每行插入的昂贵循环。 (可选)您可以将其包装在函数中。使用简单SQL函数的示例:

CREATE OR REPLACE FUNCTION fill_invoice2(in_num integer)
  RETURNS void AS
$func$
   INSERT INTO invoice(ID,INVOICE_ID,SUBSCRIBER_ID,AMOUNT,INVOICE_DATE,RECORD_DATE
                      ,INVOICE_TYPE,REST_TO_PAY,DESCRIPTION,INVOICE_REFERENCE)
   SELECT g,g,g,100,current_date,current_date,1,100,'Telco services',1111
   FROM   generate_series(0,10) g
   WHERE  $1 > 1;
$func$  LANGUAGE sql;

与原作相同。

对于某些列,我还会考虑列默认值。例如:

ALTER TABLE invoice
   ALTER COLUMN invoice_date SET DEFAULT current_date
 , ALTER COLUMN record_date  SET DEFAULT current_date;

详细说明:

然后,不要在INSERT语句中提及这些列,并自动填写默认值。