--產生流水號
--建立測試表
create table test(id varchar(18), --流水號,日期(8位)+時間(4位)+流水號(4位)
name varchar(10) --其他欄位
)
go
--建立產生流水號的觸發器
create trigger t_insert on test
INSTEAD OF insert
as
declare @id varchar(18),@id1 int,@head varchar(12)
select * into #tb from inserted
set @head=convert(varchar,getdate(),112)+replace(convert(varchar(5),getdate(),108),':','')
select @id=max(id) from test where id like @head+'%'
if @id is null
set @id1=0
else
set @id1=cast(substring(@id,13,4) as int)
update #tb set @id1=@id1+1
,id=@head+right('0000'+cast(@id1 as varchar),4)
insert into test select * from #tb
go
--插入資料,進行測試
insert into test(name)
select 'aa'
union all select 'bb'
union all select 'cc'
--修改系統時間,再插入資料測試一次
insert into test(name)
select 'aa'
union all select 'bb'
union all select 'cc'
--顯示測試結果
select * from test
--刪除測試環境
drop table test
/*--測試結果
id name
------------------ ----------
2004022720430001 aa
2004022720430002 bb
2004022720430003 cc
2004022720430004 aa
2004022720430005 bb
2004022720430006 cc
(所影響的行數為 6 行)
--*/