高分请教数据库(SQL)文件编码的问题!!!

来源:百度知道 编辑:UC知道 时间:2024/06/10 20:27:24
我在做一个文件编码的数据库,里面有个编号的标准是:HY + year + month + day + 文件流水号(01,02....) ,想请教如果当数据插入时,自动生成一个编号,该怎么处理!

很明显的用触发器写,说实话真一点难度都没,你理下思路就出来啦。
HY + year + month + day这个不说了,轻松取得。
关键是流水号,首先先检索表里是否有该天的 HY + year + month + day打头的记录(比如今天是20090422,今天的第一个编号就该是HY2009042201)如果有则倒序排序取得最大的一个编号值,然后再此基础上加1,添加进表,如果没有HY + year + month + day 打头的记录则生成流水号为01不就完了么?
一点都不难对吗??
都说到这份上了,干脆写给你得了;;
create trigger trig_insert on table1 for insert
as
begin
declare @year char(4),@month char(2),@day char(2),@count,@id varchar(15),@temp varchar(5)
set @year=year(getdate())
set @month=month(getdate())
if @month<10
set @month='0'+@month
set @day=day(getdate())
if @day<10
set @day='0'+@day
set @count=(select count(*) from table1 where left(id,10)='HY'+@year+@month+@day)
if @count>=1
begin
set @temp=cast(cast(replace((select top 1 id from table1 where left(id,10)='HY'+@year+@month+@day order by id desc),'HY'+@year+@month+@day,'') as int)+1 as varchar(5))
if @temp<1