Am creating a database in SQL and one of the field of my table is customer_id. I want this customer_id to be auto generated and auto increment. I was reading about Identity but it was too complicated to grasp. So how can that be done in a very simple way.
Thanks
As you create a table you specify the identity attribute. Then whenever you insert a row into the table, you will not need to specify a value for the identity column rather the database will do it for you.
Code Snippet
CREATE TABLE customers ( cust_id int identity(1,1), Name char(20) )
The first value is the seed and the second value is the increment. The seed is what value the sequence starts at and the increment is how much the identity column gets incremented after each insert.
Code Snippet
insert customers (Name) values ('Bill')
insert customers (Name) values ('Hank')
insert customers (Name) values ('Joe')
select *
from customers
Notice how you didn't need to specify a value for the identity column.
Code Snippet
cust_id Name
--
1 Bill
2 Hank
3 Joe
Bill gets an id of 1 since he was the first row inserted and thus gets the seed value. The identity value is now at 1. Hank gets a 2 because he gets the current identity value + increment value (1+1). The identity value is now at 2. Joe gets a 3 because he gets the current identity value + increment value (2+1).
|||Hi.Thanks for replying.
Well to be more precise i am creating the SQL database within Visual Basic Express Edition(http://msdn2.microsoft.com/en-us/library/ms172599(VS.80).aspx).
As such am not typing any code, just creating table like in access.
So how should i do from there. Dont know where to find the coding when i have creating the table.|||
I believe that if you examine the properties for each column (in the lower part of the table design window), you will see that there is a property for IDENTITY. Set that property to Yes/True.
|||Hi.thanks for replying. so stupid from my part.
No comments:
Post a Comment