Reputation: 63
CREATE TABLE Persons
(
P_Id varchar(6) NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
PRIMARY KEY (P_Id)
)
in this table P_Id
is the primary key. We want to generate autoincrement of P_Id
with default value (PN00) in the start while inserting only LastName and FirstName .eg :-PN001 for first entry ,PN002 for second,PN003 for third and so on .
Upvotes: 3
Views: 4590
Reputation: 1406
There are different ways to address your issue.
This approach wont have coupling with the table's schema.
Refer this link for more information on Triggers : https://msdn.microsoft.com/en-IN/library/ms189799.aspx
Refer this link to emulate 'before insert trigger' in SQL Server: How to emulate a BEFORE INSERT trigger in T-SQL / SQL Server for super/subtype (Inheritence) entities?
You could also use a Procedure like :
create procedure Persons_insert(@lastname varchar(255), @firstname varchar(255))
as
begin
--write code to generate the ID as you like
insert into Persons(p_id,lastname,firstname)values(generated_id,lastname,firstname);
end
Upvotes: 0
Reputation: 754388
The only viable solution is to use
ID INT IDENTITY(1,1)
column to get SQL Server to handle the automatic increment of your numeric valueSo try this:
CREATE TABLE dbo.Persons
(ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
P_ID AS 'PN' + RIGHT('00000' + CAST(ID AS VARCHAR(5)), 5) PERSISTED,
.... your other columns here....
)
Now, every time you insert a row into Persons
without specifying values for ID
or P_ID
:
INSERT INTO dbo.Persons(Col1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)
then SQL Server will automatically and safely increase your ID
value, and P_Id
will contain values like PN00001
, PN00002
,...... and so on - automatically, safely, reliably, no duplicates.
Upvotes: 8