Use this example to see the core idea, then work through the complete steps below. Code snippets are Classic ASP / VBScript or SQL Server T-SQL as labelled, not PHP.
SQL example
CREATE TABLE dbo.auto (
id INT IDENTITY(100,2) NOT NULL PRIMARY KEY,
name NVARCHAR(50) NOT NULL,
city NVARCHAR(50) NULL
);
INSERT INTO dbo.auto (name, city) VALUES (N'Ana', N'Pune');
SELECT id, name, city FROM dbo.auto;The first inserted row has ID 100 and the next normally has 102. Identity values can have gaps and should not be treated as gap-free counters.
The SQL Server IDENTITY(seed, increment) property automatically generates a numeric value when a row is inserted. It is commonly used for surrogate keys and reference numbers.
An IDENTITY property generates values, but if the column must be unique, enforce that requirement with a PRIMARY KEY or UNIQUE constraint.
CREATE TABLE dbo.auto (
id INT IDENTITY(100,2) NOT NULL CONSTRAINT PK_auto PRIMARY KEY,
name NVARCHAR(50) NULL,
city NVARCHAR(50) NULL
);The first generated value is 100 and the next is 102 because the seed is 100 and the increment is 2. Gaps can occur; applications should not assume identity values are gap-free.
INSERT INTO dbo.auto (name, city)
VALUES (N'John Reid', N'London');SQL Server generates the id automatically. In SQL Server Management Studio, the same property appears under the column's Identity Specification.
To retrieve the value generated for the row inserted by the current request, continue to SCOPE_IDENTITY() and inserted identity values.
Deleted rows, transaction rollbacks, caching, and failed inserts can leave gaps. Do not use the last identity value to calculate the exact number of records.
Use SCOPE_IDENTITY() or OUTPUT INSERTED.id with the insert batch, rather than IDENT_CURRENT() in a shared database.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| Iswarya | 03-10-2011 |
| i want to generate auto generated id like sk100001 through stored procedure in sql server 2008 | |
| mani | 24-11-2014 |
| I want to generate auto increment id like abc001 using mysql | |