473,809 Members | 2,660 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Get the generated value of serial type field (primary key)

66 New Member
Expand|Select|Wrap|Line Numbers
  1. -- Table: public.customers
  2. CREATE TABLE public.customers (
  3.   customercd   serial NOT NULL,
  4.   pass         char(32) NOT NULL,
  5.   lnamek       varchar(20) NOT NULL,
  6.   fnamek       varchar(20) NOT NULL,
  7.   status       boolean NOT NULL DEFAULT true,
  8.   /* Keys */
  9.   CONSTRAINT customers_pkey
  10.     PRIMARY KEY (customercd)
  11. ) WITHOUT OIDS;
  12.  
  13. CREATE INDEX customers_index01
  14.   ON public.customers
  15.   (customercd, status);
Expand|Select|Wrap|Line Numbers
  1. -- Table: public.customercontacts
  2. CREATE TABLE public.customercontacts (
  3.   customercd  integer NOT NULL,
  4.   contact     varchar(50) NOT NULL,
  5.   "type"      varchar(3),
  6.   /* Keys */
  7.   CONSTRAINT customercontacts_pkey
  8.     PRIMARY KEY (contact),
  9.   /* Foreign keys */
  10.   CONSTRAINT foreign_key01
  11.     FOREIGN KEY (customercd)
  12.     REFERENCES public.customers(customercd)
  13.     ON DELETE RESTRICT
  14.     ON UPDATE CASCADE
  15. ) WITHOUT OIDS;
1) insertCustomer(pass, fnamek, lnamek)
-- no need to provide the customercd and status because auto-increment and with default value respectively.

2) insertCustomerC ontact(customercd, contact, type)
-- need to provide the all fields.

Problem: How can I determine the previously used customercd that generated by the serial field upon insertCustomer in order to pass the customercd as argument to insertCustomerC ontact.
Aug 10 '07 #1
6 6260
eros
66 New Member
I found something that may be the solution..but please confirmed by the expert...

This is safe to use? That the value of last_value field from customers_custo mercd_seq is always the previously used/added upon insert?
Expand|Select|Wrap|Line Numbers
  1. insert into customercontacts (customercd, contact, 'type')
  2. values (select last_value from customers_customercd_seq,'09084789545', 'MOB');
BUT error occurred Error:
ERROR: syntax error at or near "'type'";
Error while executing the query (State:42601, Native Code: 7)



When I removed the single quote ( ' ) :
Expand|Select|Wrap|Line Numbers
  1. insert into customercontacts (customercd, contact, type)
  2. values (select last_value from customers_customercd_seq,'09084789545', 'MOB');
also error occurred:
Error: ERROR: syntax error at or near "select";
Error while executing the query (State:42601, Native Code: 7)


I am using WinSQL via ODBC
Aug 10 '07 #2
michaelb
534 Recognized Expert Contributor
Try this:
Expand|Select|Wrap|Line Numbers
  1. insert into customercontacts (customercd, contact, type)
  2. values 
  3. (select last_value, '09084789545', 'MOB' from customers_customercd_seq,)
  4.  
Aug 10 '07 #3
michaelb
534 Recognized Expert Contributor
As far as getting the last auto number getting it off the last_value field is not the best option. This field shows the last value allocated by any session, meaning that if you have concurrent or nearly concurrent processes you may get the wrong value. I would recommend using the currval function instead.

Generally speaking having to obtain the previously auto generated number is a red flag.
If you are doing some class project it's ok, but if you are working on a real life application we may need to consider other options.
Aug 10 '07 #4
eros
66 New Member
As far as getting the last auto number getting it off the last_value field is not the best option. This field shows the last value allocated by any session, meaning that if you have concurrent or nearly concurrent processes you may get the wrong value. I would recommend using the currval function instead.

Generally speaking having to obtain the previously auto generated number is a red flag.
If you are doing some class project it's ok, but if you are working on a real life application we may need to consider other options.
What's the other options? It is currval function?
Aug 13 '07 #5
michaelb
534 Recognized Expert Contributor
What's the other options? It is currval function?
No, currval is the first option - getting value directly from the last_value field is simply a bad and unsafe approach.
The alternative would be to create the sequence table manually, not associating it with your key field on the data table.
In this case you will be responsible for getting the next value from the sequence and using it to insert the row in your table.
This is a trade-off, and you would need to weight pros and cons.
With what you have now everything is automated - you don't have to worry about getting the next key, or maintaining the sequence - if you drop the table the sequence gets dropped, if you create the table the sequence gets created.
But you have to do something to obtain the key of your record, which is from the purist point of view pretty bad.
If you manage the keys manually you don't have to do anything to find its value - you have it; but on the other hand you are responsible for the whole business of maintaining the sequence table and getting the values from there.
I had experience with both of this techniques, there's no "better" way, but there is a way that could be better for a particular situation.
Follow these links for more information:
http://www.postgresql.org/docs/8.2/s...esequence.html
http://www.postgresql.org/docs/8.2/s...-sequence.html
Aug 14 '07 #6
eros
66 New Member
No, currval is the first option - getting value directly from the last_value field is simply a bad and unsafe approach.
The alternative would be to create the sequence table manually, not associating it with your key field on the data table.
In this case you will be responsible for getting the next value from the sequence and using it to insert the row in your table.
This is a trade-off, and you would need to weight pros and cons.
With what you have now everything is automated - you don't have to worry about getting the next key, or maintaining the sequence - if you drop the table the sequence gets dropped, if you create the table the sequence gets created.
But you have to do something to obtain the key of your record, which is from the purist point of view pretty bad.
If you manage the keys manually you don't have to do anything to find its value - you have it; but on the other hand you are responsible for the whole business of maintaining the sequence table and getting the values from there.
I had experience with both of this techniques, there's no "better" way, but there is a way that could be better for a particular situation.
Follow these links for more information:
http://www.postgresql.org/docs/8.2/s...esequence.html
http://www.postgresql.org/docs/8.2/s...-sequence.html
Yes, I realized that you are strongly correct. I need to have a table that maintain all the keys.

On the case of manually maintain keys in the table, I can also automate the generation of keys based on the table.

Thank you very much.
Aug 15 '07 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

5
3093
by: Paul Lamonby | last post by:
Hi, i want to create a unique serial number to my Db entries. I thought the best way would be to add the auto_increment primary key value to a string, then insert it into a table field 'serial_num'. $serial_num = "NAME000" . $auto_increment_value; Is this possible in one function? Or do I have to insert all the other data first, then get the last inserted id value and then update the
5
3041
by: Marek Lewczuk | last post by:
I'm curious if the default scheme for sequence name (which is created with SERIAL data type) can be changed -- currently all sequences are named like this: <table_name>_<field_name>_seq -- can it be changed for e.g. <table_name>__<field_name>__seq ??? Thanks. ML
3
3583
by: Poul Møller Hansen | last post by:
Hi, I need an auto incrementing field that will contain values like N000001, N000002, N000003 etc. I think the way is to use the value from an identity field in a stored procedure that is triggered at insert. I can't see that it can be made in pure SQL, but Java is not a problem. Any of you that can tell me the way of doing it ?
12
4787
by: Prabu Subroto | last post by:
Dear my friends... I am using postgres 7.4 and SuSE 9.1. I want to use auto_increment as on MySQL. I look up the documentation on www.postgres.com and I found "serial" . But I don't know how to create auto_increment. here is my try:
6
4853
by: jjturon | last post by:
Can anyone help me?? I am trying to pass a Select Query variable to a table using Dlookup and return the value to same select query but to another field. Ex. SalesManID SalesManName AT Alan Time
33
3365
by: bill | last post by:
In an application I am writing the user can define a series of steps to be followed. I save them in a sql database using the field "order" (a smallint) as the primary key. (there are in the range of 20 steps) On the admin page the steps are listed, in "order" order and the user can create new steps and assign an order and all is well. The problem may come in using a renumber function which should take the steps in their current order...
6
2923
by: Andrus | last post by:
I need to create generic table field level cache. Table primary key (PrimaryKeyStructType) can be int, string or struct containing int and string fields. FieldName contains table field name to be cached. Remove() should remove table row from cache. Row is identified by table primary key. Trying compile class causes error Operator '==' cannot be applied to operands of type
8
1848
by: Elfae | last post by:
I have searched high and low for a sample for this, and I just can't find any. Sorry for the length! Background Information The issue revolves around setting up a system-generated increase in two of a three-part field - one numeric the other text. The Org Number, Incremental Number, and Subcontractor Designation make up the Audit Identification number(7) for queries and reports. There is a hyphen between Org Number and Incremental...
1
11912
by: Frank Swarbrick | last post by:
We're trying to take advantage of the new ROW CHANGE TIMESTAMP option. Here is a simple table: CREATE TABLE "ACCTASGN"."NUMBER_STATUS" ( "STATUS_CODE" CHAR(1) NOT NULL , "STATUS_DESCRIPTION" VARCHAR(40) NOT NULL , "LAST_UPDATE" TIMESTAMP NOT NULL GENERATED ALWAYS FOR EACH ROW ON UPDATE AS ROW CHANGE TIMESTAMP
0
9603
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10640
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10376
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10387
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7662
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6881
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5689
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4332
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3861
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.