2016-04-08 19 views
1

tablosuna veri eklemek ve uid veri türü serial ile döndürmek için kullanılabilecek bir işlev oluşturmak istiyorum."HATA: sorgu sonuç verisi için hedef yok" PL/pgSQL işlevinde

CREATE TABLE uuser (
    uid serial PRIMARY KEY 
, user_name text NOT NULL 
, last_login timestamptz NOT NULL DEFAULT current_timestamp 
, real_name text 
, age int 
, city text 
, CHECK (age > 0 and age < 140) 
); 

CREATE OR REPLACE FUNCTION ins_uuser(p_user_name text 
            , p_real_name text 
            , p_age int 
            , p_city text) 
RETURNS integer AS 
$$ 
BEGIN 
INSERT INTO uuser(user_name, last_login, real_name, age, city) 
VALUES($1, CURRENT_TIMESTAMP, $2, $3, $4) 
RETURNING uid; 
END; 
$$ 
LANGUAGE plpgsql VOLATILE; 

SELECT ins_uuser('Joker', 'Jack', 18, 'New York') AS uuser_id; 
ERROR: query has no destination for result data 
CONTEXT: PL/pgSQL function ins_uuser(text,text,integer,text) line 3 at SQL statement 

cevap

1

Bunun için PL/pgsql gerekmez:

CREATE OR REPLACE FUNCTION ins_uuser(p_user_name text, p_real_name text, p_age int, p_city text) 
RETURNS integer AS 
$$ 
    INSERT INTO uuser(user_name, last_login, real_name, age, city) 
    VALUES($1, CURRENT_TIMESTAMP, $2, $3, $4) 
    RETURNING uid; 
$$ 
LANGUAGE sql VOLATILE; 

Ama gerçekten (genellikle yavaş olmasına rağmen) PL/pgsql kullanmak istiyorsanız ne yapmanız gerekiyor hata mesajı şöyle der: bazı değişkende sonucunu saklamak gerekir:


CREATE OR REPLACE FUNCTION ins_uuser(p_user_name text, p_real_name text, p_age int, p_city text) 
RETURNS integer AS 
$$ 
declare 
    new_id integer; 
BEGIN 
    INSERT INTO uuser(user_name, last_login, real_name, age, city) 
    VALUES($1, CURRENT_TIMESTAMP, $2, $3, $4) 
    RETURNING uid 
    into new_id; --<<< this stores the result in the variable 

    return new_id; 
END; 
$$ 
LANGUAGE plpgsql VOLATILE; 
+0

çalışıyor! Çok teşekkür ederim! –

İlgili konular