How To Increment A Field Value By Function

From: cn <cn(at)mail(dot)sinyih(dot)com(dot)tw>
To: pgsql-sql(at)postgresql(dot)org
Subject: How To Increment A Field Value By Function
Date: 2000-11-01 03:17:52
Message-ID: 39FF8B60.12A6F545@mail.sinyih.com.tw
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Hello!

I have read pgsql online docs but still need helps. (And pardon me for
cross posting to pgsql-novice as I have not received responses to my
problem.)

I want to increment the value of field SocialSecurityNo in a centrally
controlled table SocialSecurityTable. SocialSecurityTable contains only
one row and one field - SocialSecurityNo. Because, I think,
SocialSecurityNo in SocialSecurityTable should not even be read by any
other user when it is being incremented by a user (or the number will
duplicate), and setting transaction isolation level seems to be not
restrictive enough in this case, I use table lock as follows:

CREATE FUNCTION GetAndSetNextNumber () RETURNS TEXT AS '
DECLARE
UsedNumber TEXT;
BEGIN
BEGIN WORK;
LOCK SocialSecurityTable IN ROW EXCLUSIVE MODE;
SELECT SocialSecurityNo INTO UsedNumber FROM SocialSecurityTable;
--Do a lot of calculation on UsedNumber
-- and generate the next free SocialSecurityNo
-- and assign this free value to UsedNumber.
UPDATE SocialSecurityTable SET SocialSecurityNo=UsedNumber;
COMMIT WORK;
RETURN UsedNumber;
END;' LANGUAGE 'plpgsql';

Question A: Is this above function apporpriately designed, or are there
more efficient ways than table locking?

Question B: I think statement "LOCK SocialSecurityTable IN ROW EXCLUSIVE
MODE;" will fail when this user (user A) executed this statement AFTER
another user (user B) and user B has not yet COMMITed his transaction?
What are the solutions for this (LOCK TABLE fails in function)?

Regards,

CN

Browse pgsql-sql by date

  From Date Subject
Next Message Marc Rohloff 2000-11-01 08:02:22 Outer Joins
Previous Message George Henry C. Daswani 2000-10-31 21:52:41 Problem with coalesce..