RSS Forums RSS
Please support our MS SQL advertiser: Programming Forums

Autonumber in a SQL Server table

Join Date: Jun 2005
Location: Kansas City, Missouri, USA
Posts: 345
Reputation: Troy is an unknown quantity at this point 
Rep Power: 4
Solved Threads: 4
Troy's Avatar
Troy Troy is offline Offline
Posting Whiz

Re: Autonumber in a SQL Server table

  #8  
Jun 12th, 2005
I found a page on techonthenet.com that explained an Oracle sequence better than I could have, so I plagerized it. Below is what it said. I think it makes it clear that a sequence object maintains a unique number but is not tied to a table entitity. Yes, in practice, you normally create a sequence for a specific table, and you then only use it on that one table, but there is nothing about the sequence that prevents you from using it anytime you want. You can even just "SELECT supplier_seq.nextval" to increment the counter arbitrarily.

Quoted from techonthenet.com:
----------------------------------------------------------
In Oracle, you can create an autonumber field by using sequences. A sequence is an object in Oracle that is used to generate a number sequence. This can be useful when you need to create a unique number to act as a primary key.

The syntax for a sequence is:
CREATE SEQUENCE sequence_name
MINVALUE value
MAXVALUE value
START WITH value
INCREMENT BY value
CACHE value;

For example:
CREATE SEQUENCE supplier_seq
MINVALUE 1
MAXVALUE 999999999999999999999999999
START WITH 1
INCREMENT BY 1
CACHE 20;

This would create a sequence object called supplier_seq. The first sequence number that it would use is 1 and each subsequent number would increment by 1 (ie: 2,3,4,...}. It will cache up to 20 values for performance.

Now that you've created a sequence object to simulate an autonumber field, we'll cover how to retrieve a value from this sequence object. To retrieve the next value in the sequence order, you need to use nextval.

For example:

supplier_seq.nextval

This would retrieve the next value from supplier_seq. The nextval statement needs to be used in an SQL statement. For example:
INSERT INTO suppliers
(supplier_id, supplier_name)
VALUES
(supplier_seq.nextval, 'Kraft Foods');

This insert statement would insert a new record into the suppliers table. The supplier_id field would be assigned the next number from the supplier_seq sequence. The supplier_name field would be set to Kraft Foods.
Troy Wolf is the author of SnippetEdit. "Website editing as easy as it gets." IX Web Hosting
Reply With Quote  
Forums | Blogs | Tutorials | Code Snippets | Whitepapers | RSS Feeds | Advertising
All times are GMT -4. The time now is 10:42 am.
Newsletter Archive - Sitemap - Privacy Statement - Acceptable Use Policy - Contact Us
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC