zoukankan      html  css  js  c++  java
  • 转载自:http://dotnet.mblogger.cn/workhyj/posts/5882.aspx

    问题:在实际业务处理中有些单号需要自动增长,但又不能用自增列代替
          eg:  P031106001   -- 第一位P表示采购单,031106表示日期,后三位是流水号。 

    /* 1:创建测试用的表结构 */
    create table tablename(pono char(10),b int)
    go
    /* 2:创建一个得到当前日期的视图,为下面的自字义函数作准备 */
    create view vGetdate
    as
      select getdate() as today
    go
    /* 3:用自定义函数来得到单号(因自定函数内不能用getdate()来得到当前日期,要用到上面的视图) */
    create function getDH()
    returns char(10)
    As
    begin
        declare @dh1 char(10),@dh2 char(10)
        select @dh1 = max(pono) from  tableName
        Set @dh1 = IsNull(@dh1,'P000000000') 
        select @dh2 = Left(@dh1,1) + right(convert(varchar(8),today,112),6) + '001' from vGetdate
        if @dh1 >= @dh2
        begin
            set @dh2 = left(@dh1,7) + right('000'+ cast(cast(right(@dh1,3) as int)+1 as varchar),3)
        end   
        return(@dh2)
    end
    go
    /* 4:在字段默认值中填入 dbo.getdh() */
    alter table tablename add constraint df_tablename_1 default(dbo.getdh()) for pono
    -/* 5:测试:*/
    insert tablename(b) values(1)
    insert tablename(b) values(2)
    Select * from tablename
    -- 测试结果
    pono       b          
    ---------- -----------
    P031115001 1
    P031115002 2
    总结:此方法运用到了一些小技巧
    1:用字段默认值来实现单号自增
    2:用自定义函数来得到字段的默认值
    3:因在自定义函数中不能用getdate()之类非确定的函数,用视图来得到当前日期

  • 相关阅读:
    LeetCode 842. Split Array into Fibonacci Sequence
    LeetCode 1087. Brace Expansion
    LeetCode 1219. Path with Maximum Gold
    LeetCode 1079. Letter Tile Possibilities
    LeetCode 1049. Last Stone Weight II
    LeetCode 1046. Last Stone Weight
    LeetCode 1139. Largest 1-Bordered Square
    LeetCode 764. Largest Plus Sign
    LeetCode 1105. Filling Bookcase Shelves
    LeetCode 1027. Longest Arithmetic Sequence
  • 原文地址:https://www.cnblogs.com/rhythm/p/252787.html
Copyright © 2011-2022 走看看