2017-05-31 120 views
-1

我有這個功能的問題,並不知道如何解決它。語法錯誤處於或接近「,」,「

Create Function Quy(sdate timestamp) 
returns integer as $$ 
declare 
     numbmonth integer; 
     quy integer; 
Begin 
    numbmonth := Date_part('month',sdate); 
    If numbmonth < 4 then 
     quy := 1; 
    else if numbmonth < 7 then 
     quy := 2; 
    else if numbmonth < 10 then 
     quy := 3; 
    else quy := 4; 
    return quy; 
END; 
$$ 
LANGUAGE plpgsql; 

發生這種情況時,我嘗試運行代碼:

ERROR: syntax error at or near ";" 
LINE 16: END; 

我真的不明白什麼是錯。

+0

試圖消除;結束後? – Jan

回答

3

多個語法錯誤。該功能將像這樣工作:

CREATE OR REPLACE FUNCTION quy(sdate timestamp) 
    RETURNS integer AS 
$func$ 
DECLARE 
    numbmonth integer := date_part('month', sdate); 
    quy integer; 
BEGIN 
    IF numbmonth < 4 THEN 
     quy := 1; 
    ELSIF numbmonth < 7 THEN 
     quy := 2; 
    ELSIF numbmonth < 10 THEN 
     quy := 3; 
    ELSE 
     quy := 4; 
    END IF; 
    RETURN quy; 
END 
$func$ LANGUAGE plpgsql; 

Consult the manual for the basic syntax of IF.

但是,這是無事生非。爲了拿到年終的季度使用字段說明QUARTERdate_part() or EXTRACT()在一個簡單的表達式:

EXTRACT(QUARTER FROM $timestamp) 

EXTRACT是SQL同等標準的date_part()
或者返回double precision,如果您需要的話,則轉換爲integer::int)。

如果您仍需要一個功能:

CREATE OR REPLACE FUNCTION quy(sdate timestamp) 
    RETURNS int LANGUAGE sql IMMUTABLE AS 
'SELECT EXTRACT(QUARTER FROM $1)::int'; 

$1是參照一日功能參數。在本例中相當於sdate$ -notation適用於任何版本的Postgres,而SQL函數中的命名參數引用僅在Postgres 9.2中引入。請參閱:

dbfiddle here

+0

第一個函數在最後一行出現語法錯誤,第二個函數返回結果5,並且可以解釋datep_part中的$ 1對我有用嗎?我是SQL新手 –

+0

@ Mr.X:對不起,簡單函數中的表達式有一個錯誤。我修好了它。但在第一個語法錯誤?我不這麼認爲。查看演示:http://dbfiddle.uk/?rdbms=postgres_9.6&fiddle=8d39a48305ac72031b6f4c09883414b9您應該*始終*提供您的Postgres版本以及任何相關問題。 –

+0

非常感謝你的幫助,現在運作良好 –

相關問題