CREATE PROCEDURE AutoNum
@tb varchar(50),
@fd varchar(50)
AS
declare @p int
declare @strSQL nvarchar(250)
IF OBJECT_ID(N'tempdb..##AutoNumTmp') IS NULL CREATE TABLE [##AutoNumTmp] (ID varchar(100),FD int)
select @p=fd from ##autonumtmp where id=@tb+@fd
if @p is not null
update ##autonumtmp set fd=convert(varchar,@p+1) where id=@tb+@fd
else
exec ('insert into ##AutoNumTmp select ''' + @tb +@fd+''' as id,max('+@fd+') as fd from '+@tb)
select @strSQL='update ' + @tb + ' set ' +@fd+'=1+isnull((select fd from ##autonumtmp where id='''+@tb+@fd+'''),0) where '+@fd+' =-1'
exec sp_executesql @strsql
GO
在表insert触发器中加入autonum 表名,字段名,如autonum 'table1','ID'
设计时对应字段名类型为整型,默认值为-1
使用SQL的标识有一些不能预料的限制,用以上代码速度也比较快,完全能取代标识