Wednesday, May 03, 2006

ANSI And TSQL way of incrementing row no.!!

Hi someone today asked me to add column with autoincrementing values each time row is inserted. So i gave them this solution.
In TSQL we can achive it by :

Create customers_TSQL ( cust_id int IDENTITY (1,1) Primary Key, cust_name varchar(20))

Insert into customers_TSQL values('John')

This will insert a customer named John with cust_id set to 1.Each time a new customer is added cust_id is incremented by 1.
As we can see in create statement we have used IDENTITY (1,1) which says the IDENTITY property is what makes the column increment by 1 when a new row is added. The (1,1) after IDENTITY indicates the seed and increment value can be set when the table is created. If you wanted to have an initial value of 10 and increment it by 5 each time a record is added, you would use (10,5). You can also omit the (seed, increment value) part of the IDENTITY property, in which case the values default to one and one.

While in ANSI what we can do is:

Create customers_ANSI ( cust_id int Primary Key, cust_name varchar(20))

Insert into Customers_ANSI
Select COALESCE(MAX(cust_ID)+1,1),'John' FROM Customers_ANSI

Every time the above statement is executed it will insert value 1 greater than the max value of cust_id.

See COALESCE() in online help for further info.

1 comment:

Filipe AlvesFerreira said...

Dear Shekhar,

I would like to meet you by e-mail, b-cause using :
datevalue, datevalors, datevaleur,datevaluer,datevalors & etc.

Best regards & thank you for yours blogs/Filipe