数据库中编号字段设置为主键。在访问页面时(或保存页面信息时),从数据中取值,即取id最大值。
Public Function GetMaxID(ByVal strTable As String) As Integer
Dim iValue As Integer
cm = New SqlClient.SqlCommand("SELECT IDENT_CURRENT('" & strTable & "')", cn)
cn.Open()
dr = cm.ExecuteReader()
dr.Read()
Try
iValue = dr.GetValue(0)
Catch
iValue = 0
End Try
cn.Close()
Return iValue
End Function
Public Function GetMaxID(ByVal strTable As String) As Integer
Dim iValue As Integer
cm = New SqlClient.SqlCommand("SELECT IDENT_CURRENT('" & strTable & "')", cn)
cn.Open()
dr = cm.ExecuteReader()
dr.Read()
Try
iValue = dr.GetValue(0)
Catch
iValue = 0
End Try
cn.Close()
Return iValue
End Function
提示:amylqt(小妹)他说的是在保存的时候
在这个函数中LOCK来锁住得到编号的代码就可以了。
{
lock(typeof(SqlAccess))//SqlAccess是本静态函数所在的类。
{
double doubIdkey=-1;
string strSQL;
strSQL="select idkey from "+SqlAccess.strGetKeyTable
+" where tablename='"+strTable+"'";
object objIdkey=SqlAccess.ExecuteScalar(strSQL);
if(objIdkey==null)
{
strSQL="insert into "+SqlAccess.strGetKeyTable
+"(tablename,idkey) values('"+strTable+"',1)";
if(SqlAccess.ExecSQL(strSQL))
{
doubIdkey=1;
}
}
else
{
doubIdkey=double.Parse(objIdkey.ToString())+1;
strSQL="update "+SqlAccess.strGetKeyTable
+" set idkey=idkey+1 where tablename='"+strTable+"'";
if(!SqlAccess.ExecSQL(strSQL))
{
doubIdkey=-1;
}
}
return doubIdkey;
}
表中单据编号采用自增字段。如果不满意自增字段的INT型,想产生自己的格式,当然也可以用自己的方法来生成唯一编号。但henryfan1的方法不可取,生成一个编号居然前端应用程序进行,即使正确,效率将及其低下(多次交互,并且LOCK)。如果要自己生成也要用触发器加储存过程的方法进行。