/*-----------------------------------
*以当天的日期和类别,自动生成流水号
*解决方法:触发器
*方法缺点:只能一条条插入,无法批量插入
-----------------------------------*/
--ID形式=当天日期+类别+流水号(001,002.......)
if OBJECT_ID('test') is not null
drop table test
go
create table test (id varchar(20) ,class varchar(10),value varchar(30))
insert test select '20100129-A-001','A','kk'
insert test select '20100129-A-002','A','P'
insert test select '20100129-B-001','B','BAN'
go
create trigger t_test on test
instead of insert
as
begin
declare @id varchar(20),@class varchar(10)
set @id=(select max(t.id) from test t join inserted i on t.class=i.class and substring(t.id,1,8)=convert(varchar(8),getdate(),112))
set @class=(select class from inserted)
if (@id is null)
set @id=convert(varchar(8),getdate(),112)+'-'+@class+'-001'
else
set @id=convert(varchar(8),getdate(),112)+'-'+@class+'-'+right(cast(right(@id,3) as int)+1001,3)
insert test
select @id,class,value from inserted
end
go
insert test (class,value)select 'A','apple'
insert test (class,value)select 'A','PEAR'
insert test (class,value)select 'B','BANANA'
insert test (class,value)select 'B','CAT'
insert test (class,value)select 'C','DOG'
go
select * from test
/*
id class value
-------------------- ---------- ------------------------------
20100129-A-001 A kk
20100129-A-002 A P
20100129-B-001 B BAN
20100130-A-001 A apple
20100130-A-002 A PEAR
20100130-B-001 B BANANA
20100130-B-002 B CAT
20100130-C-001 C DOG
*/
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/feixianxxx/archive/2010/01/30/5273699.aspx