我想根据学生的部门为学生生成一个唯一的ID。 我希望当部门ID为CS时,学生ID为CS0448,部门ID为IT时为IT0448,依此类推。这些ID必须增加1。
我认为我会有另一个身份并自动增加1,每个学生添加并与部门ID连接,但这不会帮助我。这将导致IT学生在CS0448旁边添加为IT0449。请帮我解决一下这个。看到这个......一定是这样的......
...
cs0439
it0441
cs0440
it0442
cs0441
cs0442
请告诉我更好的字母数字标识选项
答案 0 :(得分:2)
您可以使用trigger BEFORE insert,根据您的逻辑更改ID的值。
基本上你会做正常的选择以获得你已经拥有的下一个ID和类型(IT或CS)(我认为)。
答案 1 :(得分:2)
您可以尝试INSTEAD OF INSERT触发器,如下所示:
create table students(id varchar(10) primary key not null, Department varchar(2), Name varchar(80))
go
create trigger students_insert_PK
on students
INSTEAD OF INSERT
as
declare @id int;
declare @dept varchar(2); select @dept=Department from INSERTED;
select @id=cast(max(right(id,4)) as int) from students where Department=@dept;
set @id=isnull(@id,0)+1;
insert into students
select Department+right('0000'+cast(@id as varchar(4)),4)
, Department
, name
from INSERTED;
go
insert into students (Department,Name) values ('CS','John');
insert into students (Department,Name) values ('CS','Pat');
insert into students (Department,Name) values ('CS','Sheryl');
insert into students (Department,Name) values ('IT','Phil');
insert into students (Department,Name) values ('EE','Frank');
insert into students (Department,Name) values ('EE','Amy');
insert into students (Department,Name) values ('EE','Stu');
go
select * from students;
go
结果: