here is the sample try like this...
AutoGenerated
Primary Key Values in sqlsserver:
For Creating a Autogenerated
Sequence in sqlserver the better way is to create an identity column
in the table for using it as a primary key and then by using this
column as reference we can generate the autogenerated sequence that
consists as combination characters and numericals
|
IdentityColumn
|
Username
|
CustomAuto Sequence
|
|
1
|
Abc
|
emp_0001
|
|
2
|
Xyz
|
emp_0002
|
Lets First create a function that
accepts a integer and returns our specified Sequence i.e
CustomAutoSequence.
Create
function CustomSequence(@id int)
returns
char(10)
as
begin
return
'emp_'+right( '0000' + convert( varchar(10) , @id ), 4) ;
end
By looking at the above function
you can now think something like this passing the identity value to
this we can generate the CustomAutoSequence.
But the Question is when to call this
function and where to call this function.
The above question has two solutions.
First we can alter our
customAutoSequence Column defination like the below shown
ALTER
TABLE Table_Name
ALTER
COLUMN CustomAutoSequence as dbo.CustomSequence(IdentityColumn)
Secondly we can use triggers to add
the CustomAuto Sequence to the table when a insert statement is
executed.
CREATE
TRIGGER Insert_CustomAutoSequence ON TableName
after
Insert as
update
TableName
As
TableName.CustomAutoSequence=dbo,CustomSequence(TableName.IdentityColumn)
from
TableName
inner
join
inserted on TableName.IdentityColumn=Inserted.IdentityColumn.
Thats it ..Now you can insert the rows
like shown below.
Insert into TableName(UserName) values
('mnp')