问题
i am so confuse i want employee id is automatic generate with prefix format i know that is possible from before trigger in sql server i am follow the post http://www.aspdotnet-suresh.com/2012/04/set-custom-auto-generatedincrement.html
USE [test1]
GO
/****** Object: Table [dbo].[Users] Script Date: 03/08/2013 12:28:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Users](
[UserId] [varchar](50) NOT NULL,
[UserName] [varchar](50) NULL,
[LastName] [varchar](50) NULL,
[Location] [varchar](50) NULL,
CONSTRAINT [PK_Users] PRIMARY KEY CLUSTERED
(
[UserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
And the display is
UserId UserName LastName Location
08U13000 SureshDasari Dasari Chennai
08U13001 SureshDasari Dasari Chennai
08U13002 SureshDasari Dasari Chennai
08U13003 SureshDasari Dasari Chennai
08U13004 SureshDasari Dasari Chennai
08U13005 SureshDasari Dasari Chennai
08U13006 SureshDasari Dasari Chennai
08U13007 SureshDasari Dasari Chennai
08U13008 SureshDasari Dasari Chennai
08U13009 SureshDasari Dasari Chennai
08U13010 SureshDasari Dasari Chennai
08U13011 SureshDasari Dasari Chennai
08U13012 SureshDasari Dasari Chennai
08U13013 SureshDasari Dasari Chennai
08U13014 SureshDasari Dasari Chennai
08U13015 SureshDasari Dasari Chennai
How to automatically create the primary key that has the following series A001000001 ... A001xxxxxx in SQL?
but i want to do it from insert before trigger and this trigger work in same table and same row ex -
INSERT INTO Users (UserName,LastName,Location) VALUES('SureshDasari','Dasari','Chennai')
and userid automatic created ? like --08U13015,08U13014
i was doing it from insert into inserted table but error can not insert in inserted or deleted table
or any other method
please help me
thanks in advance
回答1:
The answer provided by @marc_s in the question is the way to do it.
In your case it would look like this:
create table Users
(
Id int identity (3000, 1),
UserId as '08U1'+right('0000'+cast(Id as varchar(5)), 5) persisted,
UserName varchar(50),
LastName varchar(50),
Location varchar(50),
constraint PK_Users primary key (UserId)
)
I would not do it like suggested here. You will have duplicates if you ever delete a row or in case of concurrency.
SQL Fiddle
来源:https://stackoverflow.com/questions/15288625/employee-id-automatic-generate-with-prefix