当我声明自定义ID时,我在主键上面临重复。添加新数据时会发生此问题。如何添加具有新ID的当前ID 这里我的代码给出了错误: 密钥'PRIMARY'的密钥'PRIMARY'Duplicate entry'CR0000002'的重复条目'CR0000002'
顺便说一下数据库cr-num VARCHAR(255),PRIMARY KEY NOT NULL
Dim crnum As String = "CR00001" '// ID loaded from/saved to...
Dim iTemp As Integer = 0
iTemp = CInt(crnum.Substring(4, crnum.Length - 4)) '// get only the #'s from String and Convert them to Integer.
iTemp += 1 '// increase the ID # + 1.
crnum = crnum.Substring(0, 4) & iTemp.ToString("00000") '// set the ID back with String and #'s formatted to 5 digit #.
答案 0 :(得分:0)
每次执行此代码时,Crnum都会初始化为CR00001。然后它增加到CR00002。因此,每次执行此部分代码时,它都会尝试使用CR00002。尝试移动crnum的初始化,或声明变量Static。
答案 1 :(得分:0)
以下是您可以尝试的示例代码。但是,您必须更改逻辑,将零添加到新数字。
var con = new SqlConnection("Data Source=YourDataSource;Initial Catalog=testdb;Integrated Security=True");
var cmd = new SqlCommand("select top 1 pk,SUBSTRING(pk,3,LEN(pk) -1 ) from testprimary order by 1 desc", con);
con.Open();
var crnum = (string)cmd.ExecuteScalar();
var iTemp = 0;
iTemp = Convert.ToInt32((crnum.Substring(4, crnum.Length - 4)));
iTemp += 1;
crnum = crnum.Substring(0, 4) + iTemp.ToString("00000");