现在的位置: 首页 > 综合 > 正文

SQL Server中根据某个字段,ID字段自动增长的实现

2012年08月19日 ⁄ 综合 ⁄ 共 1125字 ⁄ 字号 评论关闭

创建一个表,根据Description的不同,各自对应的ID起点不同,

需求:

1、管理员ID从1000开始自增,自增量为1


2、系主任ID从2000开始自增,自增量为1


3、普通教师ID从3000开始自增,自增量为1


创建表语句如下:

create table C
(
   ID int,
   Description varchar(50)
);

接下来为这个表创建触发器,如下所示:

 

create trigger tr_syit
on C for insert
as
   declare @r1 int,@c1 int,@n1 int, @r2 int,@c2 int,@n2 int, @r3 int,@c3 int,@n3 int
   
   --处理管理员编号
   select @n1 = inserted.ID from inserted;
   select @c1 = count(ID) from C where Description='管理员';
   if(@c1=1)
    set  @r1= 1000;
   else
     begin
       select @r1 = max(ID) from C where Description='管理员';
       set @r1= @r1+1;
     end
       
   --处理系主任编号  
   select @n2 = inserted.ID from inserted;
   select @c2 = count(ID) from C where Description='系主任';
   if(@c2=1)
    set  @r2= 2000;
   else
     begin
       select @r2 = max(ID) from C where Description='系主任';
       set @r2= @r2+1;
     end
       
   --处理普通教师编号
   select @n3 = inserted.ID from inserted;
   select @c3 = count(ID) from C where Description='普通教师';
   if(@c3=1)
    set  @r3= 3000;
   else
    begin
       select @r3 = max(ID) from C where Description='普通教师';
       set @r3= @r3+1;
     end
   
   --执行插入操作
   update C set ID=(case when Description='管理员' then @r1
     when Description='系主任' then @r2
     else @r3 end) where ID= (case when Description='管理员' then @n1
     when Description='系主任' then @n2
     else @n3 end);

 

 --测试用插入数据

insert into C values(1,'管理员');
 
insert into C values(1,'系主任');
 
insert into C values(1,'普通教师');

 

--查询数据
 select * from C;

结果如下图所示:插入三行数据




 

  

抱歉!评论已关闭.