生成像这样得编号 XX2007032100001

本文介绍了一种自动递增编号的生成方法,通过结合日期与数据库中已存在的最大编号来生成新的唯一编号。此方法适用于需要自动生成记录编号的场景。

    
/// <summary>
    
/// 最后一个编号 XX200703060001
    
/// </summary>
    
/// <param name="fieldName">字段ID号</param>
    
/// <param name="tableName">表得名字</param>
    
/// <returns></returns>

    public static object GetLastCode(string fieldName, string tableName, int autoBuildCodeLength)
    
{
        
string executeString = "SELECT " + fieldName + " FROM " + tableName + " WHERE LEN(" + fieldName + ") = " + autoBuildCodeLength + " ORDER BY ID DESC";
        
return Common.GetDatabase().GetFirstData(executeString, CommandType.Text);
    }


    
/// <summary>
    
/// 第一位为0
    
/// </summary>

    private static int _autoBuildCount = 0;

    
/// <summary>
    
/// 自动生成编号 如 "XXXX" + 2007030600001 这样的
    
/// "XXXX" 传来的
    
/// </summary>
    
/// <param name="codeFormat">编号得格式</param>
    
/// <param name="fieldName">字段ID号</param>
    
/// <param name="tableName">表得名字</param>
    
/// <param name="autoBuildCodeLength">自动生成编号得长度</param>
    
/// <returns></returns>

    public static string GetAutomatismBuildCode(string codeFormat, string fieldName, string tableName,int autoBuildCodeLength)
    
{
        
string yearMonthDay1 = "";
        
string yearMonthDay2 = codeFormat + DateTime.Now.Year.ToString() +
            NumberIsLessThan10(DateTime.Now.Month) 
+
            NumberIsLessThan10(DateTime.Now.Day);
        
object autoBuildCode;
        
string AutomatismNumber = "";

        autoBuildCode 
= GetLastCode(fieldName, tableName, autoBuildCodeLength);
        
if (autoBuildCode == null)
        
{
            _autoBuildCount 
= 1;
        }

        
else
        
{
            yearMonthDay1 
= autoBuildCode.ToString().Substring(0, autoBuildCodeLength-5);
            
if (yearMonthDay2 == yearMonthDay1)
            
{
                _autoBuildCount 
= int.Parse(autoBuildCode.ToString().Substring(autoBuildCodeLength-55));
            }

            
++_autoBuildCount;
        }

        AutomatismNumber 
= yearMonthDay2 + _autoBuildCount.ToString("00000");

        _autoBuildCount 
= 0;
        
return AutomatismNumber;
    }


    
/// <summary>
    
/// 判断月日是一位还是两位数
    
/// </summary>
    
/// <param name="aa"></param>
    
/// <returns></returns>

    private static string NumberIsLessThan10(int monthOrDay)
    
{
        
if (monthOrDay < 10)
        
{
            
return "0" + monthOrDay.ToString();
        }

        
return monthOrDay.ToString();
    }

 
XX2007032100001

这个每添加完一条记录时最后一位都自动加一



Trackback: http://tb.blog.youkuaiyun.com/TrackBack.aspx?PostId=1536936

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值