2010-04-19 118 views
2

我嘗試在這樣的代碼中聲明一個變量,但它不起作用。你能告訴我有什麼問題嗎?如何在PostgreSQL中聲明變量

ERROR: syntax error at or near "VARCHAR" 
LINE 2: p_country VARCHAR; 


DECLARE 
    p_country VARCHAR; 
p_country : = ''; 
SELECT p_country; 
+0

請給出關於您的問題的更多數據 – Karthik 2010-04-19 11:13:33

+0

最好像這樣寫: DECLARE p_country VARCHAR; p_country:=''; SELECT p_country; – user307880 2010-04-19 11:18:59

+0

語法有什麼問題。 – user307880 2010-04-19 11:20:06

回答

2

在一個PL/pgSQL函數可以這樣聲明變量:

CREATE FUNCTION identifier (arguments) RETURNS type AS ' 
    DECLARE 

    -- Declare an integer. 
    subject_id INTEGER; 

    -- Declare a variable length character. 
    book_title VARCHAR(10); 

     -- Declare a floating point number. 
    book_price FLOAT; 

    BEGIN 
    statements 
    END; 
' LANGUAGE 'plpgsql'; 

來源:http://www.commandprompt.com/ppbook/x19832

+0

但我想聲明一個變量的功能。可能嗎? – user307880 2010-04-19 11:46:46

+1

[Not yet](http://developer.postgresql.org/pgdocs/postgres/sql-do.html) – 2010-04-19 12:12:13

5

爲custom_variable_classes創建postgresql.conf中新設置:

custom_variable_classes = 'var' 

重新載入配置,您現在有變量「var」可用在你所有的數據庫中。

要創建變量p_country,只需使用SET:

SET var.p_country = 'US'; 
SELECT current_setting('var.p_country') AS p_country; 

這不是一個美女,但它的作品。

+0

這很有趣。但問題是我向遠程服務器發出了查詢。我不認爲我會被允許編輯postgresql.conf。 – user307880 2010-04-20 06:41:08

+0

你可以讓他們在配置中添加這個,它不是火箭科學。你也可以使用臨時表來放置你的變量。 – 2010-04-20 08:03:22