I want to create a primary key(auto-increment)
which is start with A001000001
.
Here A001
would be constant and 000001
would be iterate.
I want rows like this:
How can I do it using SQL query?
For SQL Server (you didn't clearly specify which RDBMS you're using), my suggestion would be:
INT IDENTITY
column to your table - and quite frankly, I would make that column the primary keySomething like:
CREATE TABLE dbo.YourTable
( ID INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
EmpID AS 'A001' + RIGHT('0000000' + CAST(ID AS VARCHAR(10)), 7) PERSISTED
)
That way, if you insert a row, the ID
gets set automatically, and the EmpID
will also be set automatically to values like A0010000001
, A0010000002
, .... and so forth.
If you want to put the primary key on the EmpID
column, then you need to make sure to include the NOT NULL
specification when creating it:
CREATE TABLE dbo.YourTable
( ID INT IDENTITY(1,1),
EmpID AS 'A001' + RIGHT('0000000' + CAST(ID AS VARCHAR(10)), 7) PERSISTED NOT NULL
)
and then you can put the primary key constraint on that column:
ALTER TABLE dbo.YourTable
ADD CONSTRAINT PK_YourTable PRIMARY KEY CLUSTERED (EmpID)