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;
SELECT passenger_checkANDinsert(
'john', 'levis', 'v39949455', 'British', '1990-07-23'
);
功能將插入正確的結果到數據庫中,如果我更改名字到另一個功能。但如果我更改姓氏並保持與數據庫數據相同的名字,它將不起作用。我想有東西在SELECT語句中錯在何處的功能狀態,但我找不到任何錯誤的..
抱歉輸入錯誤.. firstname是數據庫乘客表中的一列。 – johnnily 2013-04-06 19:37:36
爲什麼使用函數而不是將passengerid設置爲'SERIAL'並在表上添加唯一約束? – 2013-04-06 20:06:22
因爲passengerid類型是INTEGER。出於某種原因,我不允許更改數據類型。 – johnnily 2013-04-06 20:09:43