I am writing a unit test for my PostgreSQL functionality. This starts with inserting data in the database and then calling a certain function. However, because I use auto-incrementing IDs, I cannot know what parameter to put in my function call.
I want to be able to do something like this:
INSERT INTO myTable ...;
SELECT id FROM myTable INTO l_id;
SELECT my_function(l_id);
Updates
- I am using an SQL script, not PL/pgSQL
- In MySQL I can do this:
SELECT @id:=itemid FROM myTable;
, then later on, I can use@id
anywhere I like.
3 Answers 3
DROP SCHEMA tmp CASCADE;
CREATE SCHEMA tmp ;
SET search_path=tmp;
CREATE TABLE mytab
( id INTEGER NOT NULL PRIMARY KEY
);
INSERT INTO mytab (id) SELECT gs FROM generate_series(1,10) gs;
CREATE OR REPLACE FUNCTION tmp.myfunc ( _int integer )
RETURNS text AS
$func$
DECLARE ret text;
BEGIN
ret = 'OMG_' || _int::text;
RETURN ret;
END;
$func$
LANGUAGE 'plpgsql'
;
SELECT myfunc(1);
SELECT myfunc(mt.id)
FROM mytab mt
;
Also, for smaller things you could use psql's \gset
command : (link to documentation)
1 Comment
SELECT myFun(id) FROM table
. Should have thought of that myself.INSERT in Postgres returns an OID, which you can get in a number of ways
- Using the returning clause in normal SQL, e.g.
INSERT INTO distributors (did, dname) VALUES (DEFAULT, 'XYZ Widgets')
RETURNING did;
using the GET DIAGNOSTICS api in PL-PGSQL
using the return function in a helper library (syntax depending on library).
In your case, you could do something like
with res as (
INSERT INTO my_table (id, ...) VALUES(x,..)
RETURNING id)
SELECT my_function(res.id);
4 Comments
psql < test.sql
.did
in my function call? In a plain SQL script? MySQL for example has @
for variables.DO
block, which works fine as well (seems to be some kind of anonymous function)
SELECT
a value and use it later in the script.SELECT my_function()
call?