Sunday, February 12, 2012

Auto increment help

Is there an auto increment feature for integer key fields. I'm using VS2005 to configure my DB and I do not see a way to set this.

Thanks in Advance
MoonWa

CREATE TABLE tblArtists
(
artistID int identity primary key,
artistName nvarchar(50) NOT NULL
)

this SQL creates a table with two fields, the keyword 'identity' makes a field auto increment. In the UI there's a property 'identity specification', or something similar. If you open this, you can check 'is identity'.

|||

DataColumn type has a property AutoIncrement:

dtEmployees.Columns[0].AutoIncrement = true;
dtEmployees.Columns[0].AutoIncrementSeed = -1;
dtEmployees.Columns[0].AutoIncrementStep = -1;

SQL Server table may also have one identity column, as Christian mentioned. But you should be aware of some points:

1. SQL Server by default doesn't allows inserting in Identity columns (and never allows updates)
2. Your DataColumn instance knows nothing about current SQL Server Identity value and will possibly generate duplicate values (which will fail on insert if column is constrained via Primary Key or Unique, as usually).

So, if you let SQL Server to generate values, you also should update your column' values with generated one from stored proc output parameters or from output from FOR INSERT trigger on your table (or so) using DataAdapter. For example:

daEmployees.InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord;

WBR, Evergray
--
Words mean nothing...

|||Thanks for your help.

MoonWa

No comments:

Post a Comment