如何每年重置sql身份值?

时间:2011-10-05 22:07:49

标签: asp.net database sql-server-2008

嗨'我正在使用与学生注册相关的asp.net应用程序,将与学生相关的数据插入到数据库中,每次学生注册时,字段idStudent增加1,我想做的是当新的一年开始重置学生价值,以便从新年的1开始。

  • idStudent 2011年第1期2011年3月3日 2011 4 2011 5 2011 ..... 1 2012 2
    2012 3 2012 .......

我该怎么做? 数据库位于sql server 2008中

希望你的帮助

2 个答案:

答案 0 :(得分:1)

如果我有这个确切的业务要求而我无法协商更好,更有效的方式,那么这将是我的方法:

我不使用人工密钥(即identity列),而是使用复合密钥。要了解复合键的最佳选择,您需要了解业务规则和逻辑。换句话说,你不得不问的一个问题是是年份和唯一的组合吗?换句话说,每年学生ID只能使用一次......?

这是您从自然复合键中受益的时间之一。

答案 1 :(得分:0)

您可以添加一个计算列,该列根据年份推导出数字。你只需要在新的一年开始运行下面的脚本。请注意,当回滚事务时,标识列中将存在间隙。 (并且前一年的插入也会产生很大的差距。)

-- test table & inserts
create table Students (Id int identity, year int, name varchar(20), StudentId int null)
insert into Students (year, name) values (2010, 'student1'), (2011, 'student1'), (2011, 'student2')

-- run this every year
EXEC ('ALTER TABLE Students DROP COLUMN StudentId ')
declare @count int, @sql varchar(max), @year int

declare c cursor local read_only 
for select year + 1, max(Id) from Students group by year

open c

fetch next from c into @year, @count
select @sql = 'when year = ' + convert(varchar(10), @year - 1) + ' then Id '+ CHAR(13) + CHAR(10)
while @@FETCH_STATUS = 0 
  begin
    select @sql = @sql + 'when year = ' + convert(varchar(10), @year) + ' then Id - ' + convert(varchar(10), @count) + CHAR(13) + CHAR(10)
    fetch next from c into @year, @count
  end
close c
deallocate c
select @sql = 'CASE ' + CHAR(13) + CHAR(10) + @sql + ' ELSE 0 END'
select @sql = 'ALTER TABLE Students ADD StudentId AS ' + isnull(@sql, 'Id') + '  PERSISTED'

exec (@sql)
相关问题