注册 登录
编程论坛 SQL Server论坛

自动编号怎吗实现

雪雨星风 发布于 2007-11-24 10:31, 934 次点击
编号的组成         200711240001     年+月+日+今天的编号     
    后边依次类推  200711250001
 怎么用自动编号实现        求高手帮忙
6 回复
#2
purana2007-11-24 10:36
使用instead of触发器即可.
#3
shen5219412007-11-24 10:39
purana
帮我解决下  我那个还没解决
#4
雪雨星风2007-11-24 10:43
能不能把语句写一下:)
#5
purana2007-11-24 10:46
--生成流水号

--创建测试表
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 行)
--*/
#6
orliubc2007-11-24 12:34
哈哈,今天下午正好学习触发器呢。。学习下先。

purana , 偶强烈支持你再来几段。
;P ;P ;P
#7
雪雨星风2007-11-25 08:56
谢谢
1