CREATE OR REPLACE FUNCTION heckANDinsert(
first VARCHAR(20), surname VARCHAR(20),
No VARCHAR(30), nation VARCHAR(30), dob DATE
) RETURNS SETOF passenger AS $$
DECLARE
name VARCHAR(20);
Sname VARCHAR(20);
Pass VARCHAR(30);
nation VARCHAR(30);
birthdate DATE;
BEGIN
SELECT first, same,passportNo, nationality,dob
INTO fname,sname, PassportN, nation, birthdate
FROM passenger
WHERE
firstname = $1
AND surname = $2
AND passportNo = $3
AND nationality = $4
AND dob = $5;
IF NOT FOUND THEN
INSERT INTO passenger
SELECT MAX(passengerid)+1, $1,$2,$3,$4,$5
FROM passenger;
ELSE
RAISE EXCEPTION 'passenger record already exists.';
END IF;
END;
$$ LANGUAGE plpgsql;
I called the function using
SELECT passenger_checkANDinsert(
'john', 'levis', 'v39949455', 'British', '1990-07-23'
);
the function will insert the right result into database if i change the first name to another. but it won't work if i change the surname and remain the first name same as database data. i guess there is something wrong within the select statement WHERE condition in the function, but i can't find any error for that..
SERIAL
and putting a unique constraint on the table?serial
isn't a real datatype, it's just an alias for an integer which takes the default from a sequence. You can do that "manually" any time you want without the need to modify the datatype: sqlfiddle.com/#!12/e8548/1 Creating a unique value based onmax()
is a very bad idea. It will not work correctly and it will not scale at all.