-- 作者:青丘狐
-- 发布时间:2023/2/25 16:38:00
-- 网络环境下的复杂编号(已解决)
多表编号
上述的代码只是对一个订单表进行自动编号,如果一个项目中有多个表需要进行类似的编号,可以修改编号表的结构,包括三列,分别是:表名、前缀和顺序号,表名和前缀是字符型,顺序号是整数型。
所有需要自动编号的表的DataRowAdding事件代码依然为:
Static Index As Integer = 99999 e.DataRow("编号") = Format(Date.Today(),"yyMM") & "-" & Index Index = Index - 1
而BeforeSaveDataRow事件代码需要稍微调整一下,加上表名的条件:
Dim dr As DataRow = e.DataRow Dim pf As String If dr.RowState <> DataRowState.Added Then \'如果不是新增行 Return \'那么返回 ElseIf dr.IsNull("日期") Then \'如果没有输入日期 e.Cancel = True \'取消保存此行 MessageBox.Show("必须输入日期!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information) Return Else pf = Format(dr("日期"),"yyMM") \'否则获得编号的前缀,两位年,两位月 End If Dim cmd1 As New SQLCommand Dim cmd2 As New SQLCommand Dim Key As Integer Dim nm As String = e.DataTable.name cmd1.ConnectionName = "编号" \'设置数据源名称 cmd2.ConnectionName = "编号" cmd1.commandText = "Selec t Count(*) From [编号] Where [前缀] = \'" & pf & "\' And 表名 = \'" & nm & "\'" If cmd1.ExecuteScalar = 0 Then \'如果编号表不存在前缀的行,那么增加一行 cmd1.commandtext = "Inser t Into 编号 (表名, 前缀, 顺序号) Values(\'" & nm & "\',\'" & pf & "\',1)" cmd1.ExecuteNonQuery End If cmd1.commandText = "Selec t [顺序号] From [编号] Where [前缀] = \'" & pf & "\' And 表名 = \'" & nm & "\'" Do Key = cmd1.ExecuteScalar() \'从后台获得顺序号 cmd2.commandText = "Updat e [编号] Set [顺序号] = " & (Key + 1) & " Where [顺序号] = " & Key & " And [前缀] = \'" & pf & "\' And 表名 = \'" & nm & "\'" If cmd2.ExecuteNonQuery() > 0 Then \'更新顺序号 Exit Do \'更新成功则退出循环 End If Loop e.DataRow("编号") = pf & "-" & Format(Key,"0000")
此主题相关图片如下:dh01.png
此主题相关图片如下:dh02.png
保存后,数据库里单号没有变啊
[此贴子已经被作者于2023/2/26 20:48:14编辑过]
|
-- 作者:青丘狐
-- 发布时间:2023/2/25 17:07:00
--
DataRowAdding
\'网络编号 Static Index As Integer = 99999 e.DataRow("合同ID") = "CG" & Format(Date.Today(), "yyMM") & "-" & Index Index = Index - 1
AfterSaveDataRow
\'\'网络编号 Dim dr As DataRow = e.DataRow Dim pf As String If dr.RowState <> DataRowState.Added Then \'如果不是新增行 Return \'那么返回 ElseIf dr.IsNull("登记日期") Then \'如果没有输入日期 e.Cancel = True \'取消保存此行 MessageBox.Show("必须输入日期!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information) Return Else pf = Format(dr("登记日期"), "yyMM") \'否则获得编号的前缀,两位年,两位月 End If Dim cmd1 As New SQLCommand Dim cmd2 As New SQLCommand Dim Key As Integer Dim nm As String = e.DataTable.name cmd1.C \'设置数据源名称 cmd2.C cmd1.commandText = "Selec t Count(*) From [网络编号] Where [前缀] = \'" & pf & "\' And 表名 = \'" & nm & "\'" If cmd1.ExecuteScalar = 0 Then \'如果编号表不存在前缀的行,那么增加一行 cmd1.commandtext = "Inser t Into 网络编号 (表名, 前缀, 顺序号) Values(\'" & nm & "\',\'" & pf & "\',1)" cmd1.ExecuteNonQuery End If cmd1.commandText = "Selec t [顺序号] From [网络编号] Where [前缀] = \'" & pf & "\' And 表名 = \'" & nm & "\'" Do Key = cmd1.ExecuteScalar() \'从后台获得顺序号 cmd2.commandText = "U pdate [网络编号] Set [顺序号] = " & (Key + 1) & " Where [顺序号] = " & Key & " And [前缀] = \'" & pf & "\' And 表名 = \'" & nm & "\'" If cmd2.ExecuteNonQuery() > 0 Then \'更新顺序号 Exit Do \'更新成功则退出循环 End If Loo p e.DataRow("合同ID") ="CG" & pf & "-" & Format(Key, "0000")
此主题相关图片如下:bhb.png
|