自動(dòng)生成編號(hào)的方法
當(dāng)前位置:點(diǎn)晴教程→知識(shí)管理交流
→『 技術(shù)文檔交流 』
[p]前言:[br]用過許多序號(hào)的方法,indentity 或 new id() ,都不好用,自己寫了一個(gè),這個(gè)序號(hào)的特點(diǎn)是:每次取相應(yīng)表中的系統(tǒng)當(dāng)天最大序號(hào),如果當(dāng)天無記錄,則自動(dòng)生成一個(gè)當(dāng)天序號(hào) [/p]
[p][br]1.建種子表,這個(gè)表用來保存各個(gè)表目前已使用到的最大序號(hào).[br]--種子表[br]create table seed ([br]bm varchar(20) not null, --表名[br]bh varchar(12) not null, --種子編號(hào)[br]constraint pk_seed primary key(bm)[br])[br]go[/p] [p]2.當(dāng)我們建一個(gè)新表時(shí),同時(shí)把這個(gè)表名記錄到種子表中,如:[br]--向種子中表添加記錄[br]insert into seed (bm,bh) values('tablename','200211070000')[br]go[/p] [p]3.在數(shù)據(jù)庫建一存儲(chǔ)過程,自動(dòng)生成新編號(hào),此編號(hào)取當(dāng)天時(shí)間,所以許多時(shí)候查詢某些天的記錄時(shí),這個(gè)序號(hào)非常有用[br]--為參數(shù)傳遞來的某個(gè)表自動(dòng)生成編號(hào)[br]if exists (select * from sysobjects where name='proc_getbh')[br]drop procedure proc_getbh [br]go[br]create procedure proc_getbh @bm varchar(20) [br]as[br]declare @bh char(12)[br]declare @today char(8)[br]begin[br]select @today=convert(char(8),getdate(),112)[br]select @bh=bh from seed where [url=mailto:bm=@bm]bm=@bm[/url][br]if @bh is null or left(@bh,8)<>@today[br]begin[br]select @bh=@today+'0000'[br]end [br]select @bh=left(@bh,8)+ right('0000' + ltrim(convert(char(4),convert(int,right(@bh,4)))+1),4)[br]update seed set [url=mailto:bh=@bh]bh=@bh[/url] where [url=mailto:bm=@bm]bm=@bm[/url][br]select @bh as bh[br]end[/p] [p]4.實(shí)例如下:[br]'對(duì)表xxx自動(dòng)生成新編號(hào)[br]set rs=conn.execute("proc_getbh @bm='xxx'")[br]這樣,rs("bh")就是你得到的新編號(hào)[/p] 該文章在 2010/7/5 0:10:41 編輯過 |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |