问题描述:
   单据号生成规则:yyyymmdd(年月日)+ 000001(六位流水号,并且自增),
   单据号要求:1.每天从000001开始 2. 单据号要连续啊。
客户端体现:
    用户每次打开画面要显示按照上面自动生成的单据号。
疑难点:
     多用户操作时画面生成的单据号可能重复啊,这样插入数据库单据号就重复了!
求解决方法??

解决方案 »

  1.   

    --下面的代码生成长度为8的编号,编号以BH开头,其余6位为流水号。
    --得到新编号的函数
    CREATE FUNCTION f_NextBH()
    RETURNS char(8)
    AS
    BEGIN
    RETURN(SELECT 'BH'+RIGHT(1000001+ISNULL(RIGHT(MAX(BH),6),0),6) FROM tb WITH(XLOCK,PAGLOCK))
    END
    GO--在表中应用函数
    CREATE TABLE tb(
    BH char(8) PRIMARY KEY DEFAULT dbo.f_NextBH(),
    col int)--插入资料
    BEGIN TRAN
    INSERT tb(col) VALUES(1)
    INSERT tb(col) VALUES(2)
    INSERT tb(col) VALUES(3)
    DELETE tb WHERE col=3
    INSERT tb(col) VALUES(4)
    INSERT tb(BH,col) VALUES(dbo.f_NextBH(),14)
    COMMIT TRAN--显示结果
    SELECT * FROM tb
    /*--结果
    BH         col 
    ---------------- ----------- 
    BH000001  1
    BH000002  2
    BH000003  4
    BH000004  14
    --*/
      

  2.   

    如果在编号里记录上个GETDATE()一般就不会重复了...
      

  3.   


    得用s lock 你问问大大吧,我也不太清楚
      

  4.   

    --种子表 num_tb 
    if object_id('num_tb') is not null
    drop table num_tb
    go
    create table num_tb(d datetime,id int)
    insert num_tb select getdate(),1 
    if object_id('tb') is not null
    drop table tb
    go
    create table tb(id varchar(20),name varchar(10)) create clustered index idx_clu_tb on tb(id) 
    go create trigger tri_tb on tb 
    INSTEAD OF INSERT 
    as 
    begin 
    set nocount on 
    declare @i int,@id varchar(20),@j int 
    select @i=count(*) from inserted 
    begin tran 
    update num_tb with(TABLOCKX) set 
    id=(case when convert(char(8),d,112)=convert(char(8),getdate(),112) 
    then id+@i else @i end), 
    @j=(case when convert(char(8),d,112)=convert(char(8),getdate(),112) then id else 0 end), 
    d=getdate() 
    commit tran 
    select * into #t from inserted 
    update #t set id=convert(varchar(8),getdate(),112)+right('00000'+rtrim(@j),5),@j=@j+1 
    insert tb select * from #t 
    end 
    go 
    --插入记录测试 insert into tb(name) values('张三') 
    insert into tb(name) values('李四') 
    select * from tb
    /*
    id                   name
    -------------------- ----------
    2010012700002        张三
    2010012700003        李四
    */
    insert into   tb select '2010012700003','王五'
    /*
    id                   name
    -------------------- ----------
    2010012700002        张三
    2010012700003        李四
    2010012700004        王五*/看看这个可以满足吧?
      

  5.   

    建议这个表的主键仍用identity 自动生成。然后再触发器,或者查询中根据  单据日期,显示这个序列号。
    这样实现起业比较容易,也容易解决冲突!
      

  6.   

    建一个类似的表tb_identitytbid int, maxid int为每个要算号的表分配一个id, maxid存放每个表中自定义编号数字部分最大值就算你的库中有上千个需要自动算号的表,那这么个表中也只有几千条记录(而事实上一个系统中这样自动算号的表并不多一般几十个),每次算号时先update, 因为只update一条记录, 所以锁等待时间是很短的,也排除了断号问题。