2017-01-10 1 views
1

Voici le code exemple complet:Insérer la fonction Within échoue avec "requête n'a pas de destination pour les données de résultat"

CREATE TABLE testtbl (
    id  integer NOT NULL, 
    intval integer, 
    strval varchar(64) 
); 
CREATE SEQUENCE testtbl_id_seq 
    START WITH 1 INCREMENT BY 1 
    NO MINVALUE NO MAXVALUE CACHE 1; 
ALTER SEQUENCE testtbl_id_seq OWNED BY testtbl.id; 
ALTER TABLE ONLY testtbl ALTER COLUMN id SET DEFAULT 
    nextval('testtbl_id_seq'::regclass); 
ALTER TABLE ONLY testtbl ADD CONSTRAINT testtbl_pkey PRIMARY KEY (id); 

CREATE FUNCTION insert_testtbl (p_intval integer, p_strval varchar(64)) 
    RETURNS integer AS $$ 
    DECLARE 
    v_new_id integer; 
    BEGIN 
    INSERT INTO testtbl (intval, strval) VALUES (p_intval, p_strval) 
     RETURNING v_new_id; 
    RETURN v_new_id; 
    END; 
$$ LANGUAGE plpgsql; 

SELECT insert_testtbl(1, 'One'); 

Quand je lance cette (version PostgreSQL est 9.6.1), je reçois:

ERROR: query has no destination for result data 
CONTEXT: PL/pgSQL function insert_testtbl(integer,character varying) line 5 at SQL statement 

Cela n'a pas de sens; I AM spécifiant une destination pour le résultat!

Qu'est-ce que je fais mal ici? Merci!!!

Répondre

3

Je spécifie une destination pour le résultat!

Non, vous ne l'êtes pas.

RETURNING v_new_id; signifie simplement:
« renvoie la valeur actuelle de la v_new_id variable à partir de cette instruction d'insertion »

(qui est null que la variable n'a jamais été attribué une valeur)

Vous n'êtes pas stocker la valeur générée n'importe où.

Vous avez besoin soit d'utiliser une clause into:

CREATE FUNCTION insert_testtbl (p_intval integer, p_strval varchar(64)) 
    RETURNS integer AS $$ 
    DECLARE 
    v_new_id integer; 
    BEGIN 
    INSERT INTO testtbl (intval, strval) VALUES (p_intval, p_strval) 
     RETURNING id 
     INTO v_new_id; --<<< HERE 
    RETURN v_new_id; 
    END; 
$$ LANGUAGE plpgsql; 

Ou convertir tout simple fonction SQL:

CREATE FUNCTION insert_testtbl (p_intval integer, p_strval varchar(64)) 
    RETURNS integer AS 
$$ 
    INSERT INTO testtbl (intval, strval) VALUES (p_intval, p_strval) 
    RETURNING id; 
$$ LANGUAGE sql; 
+0

Impressionnant !! Je vous remercie!! –

+0

@RodTurnham: si cela a résolu votre problème, veuillez accepter la réponse, afin que votre question soit marquée comme résolue. –