VB.NET 前缀+日期格式+4位后缀 自动编号,例如GK201007190001

代码
''' <summary>
''' 自动编号
''' Add by pwm 2010.07.19
''' </summary>
''' <param name="str">编号的前缀</param>
''' <param name="ID">表中的主键</param>
''' <param name="TableName">表名</param>
''' <returns></returns>
''' <remarks></remarks>
Public Function AutoID(ByVal str As String, ByVal ID As String, ByVal TableName As String)
FunctionName
= "AutoID"
Dim ReturnID As String = Nothing
Try
Dim sb As New StringBuilder
With sb
.Append(
" SELECT ")
.Append(
" MAX ")
.Append(
" ( ")
.Append(ID)
.Append(
" ) ")
.Append(
" FROM ")
.Append(TableName)
End With
Dim o As Object = sqlhelp.GetObjectType(sb.ToString, CommandType.Text)
'数据库中没有数据
If o Is Nothing or o.Equals (System.DBNull.Value) Then
ReturnID
= str + Format(Now.Year, "0000") + Format(Now.Month, "00") + Format(Now.Day, "00") + "0000"
Else
'前缀的长度
Dim PreCount As Integer = str.Length
'历史日期
Dim HistoryDate As DateTime = CDate(o.ToString.Substring(PreCount, 8))
'最后几位数字组成的字符串
Dim LastString As String = o.ToString.Substring(PreCount + 8)
'当天日期>历史日期
If HistoryDate < Now.Date Then
ReturnID
= str + Format(Now.Year, "0000") + Format(Now.Month, "00") + Format(Now.Day, "00") + "0000"
'当天日期=历史日期
ElseIf HistoryDate = Now.Date Then
ReturnID
= str + Format(Now.Year, "0000") + Format(Now.Month, "00") + Format(Now.Day, "00") + Format(CInt(LastString) + 1, "0000")
End If
End If

Catch sqlex As SqlException
'抛出异常
Throw sqlex
Catch ex As Exception
'抛出异常
Throw ex
End Try

Return ReturnID
End Function

 

posted on 2010-07-20 22:04  pwm_1987  阅读(1328)  评论(0编辑  收藏  举报

导航