员工ID自动生成前缀

时间:2013-03-08 07:11:53

标签: sql visual-studio-2010 sql-server-2008 triggers

我很困惑我希望员工ID是自动生成的前缀格式 我知道在sql server中触发之前是可能的 我关注这个帖子 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

显示为

    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?

但我想从触发前的插入中做到这一点 并且此触发器在同一个表和同一行中工作 前 -

INSERT INTO Users (UserName,LastName,Location) VALUES('SureshDasari','Dasari','Chennai')

和userid自动创建?比如--08U13015,08U13014

我从插入到插入表中这样做但是错误无法插入插入或删除的表中 或任何其他方法 请帮我 提前谢谢

1 个答案:

答案 0 :(得分:1)

@marc_s在问题中提供的答案是如何做到这一点。

在你的情况下,它看起来像这样:

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)
)

我不会像建议here那样做。如果你删除了一行或者是并发的话,你将会有重复。

SQL Fiddle