Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

How to generate unique incremental employee code(pattern: E0001, E0002, E0003, ... ) in the INSERT stored procedure in SQL Server?

I want to generate unique employee code at a time of inserting a single record in INSERT stored procedure.

First-time procedure call will generate employee code as E0001, the second call will generate E0002, ...

The expected output should look like,

EmployeeCode    EmployeeName
-------------------------------
E0001           A
E0002           B
E0003           C
E0004           D
E0005           E
  '             '
  '             '
  '             '
E9999           ZZZ
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can embed a sequence value into a custom-formatted string in a default, and enforce it with a check constraint. Like this:

--drop table if exists Employee
--drop sequence seq_Employee
--go

create sequence seq_Employee
start with 1
increment by 1    
go

CREATE TABLE Employee
(
    EmployeeCode char(5) PRIMARY KEY 
        default 'E' + format((next value for seq_Employee),'0000' )
        check (EmployeeCode like 'E[0-9][0-9][0-9][0-9]'),
    EmployeeName VARCHAR(50) NOT NULL
)    
go

insert into Employee(EmployeeName)
values ('A'),('B'),('C'),('D'),('E')

select *
from Employee

Outputs

EmployeeCode EmployeeName
------------ --------------------------------------------------
E0001        A
E0002        B
E0003        C
E0004        D
E0005        E

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...