当用户填写表格时,他/她一次最多可以完成5条记录。
如果用户完成1条记录,则ID增加1。
但是,当用户完成超过1条记录时,我们希望ID增加的记录数量与用户完成的数量相同。
例如,假设ID为2516的用户完成3条记录,我们希望看到类似的内容:
ID User
1 2516
2 2516
3 2516
如果id为4874的另一个用户完成2,我们将:
ID User
4 4874
5 4874
等
相反,无论一个特定用户输入多少新记录,ID的值仅增加1。
我知道这是基于以下代码。
是否可以帮我修复一下,以便根据特定用户提交的记录数量增加值。
我们不想使用身份种子来增加它。
我们非常感谢您的帮助。
sql += "INSERT INTO Emp (UserSequence, employee_id, charity_code, check_amt, chcknum, one_time, bi_weekly, cash, donate_choice, date_stamp) "
sql += "VALUES ((select isNull(max(UserSequence), 0) + 1, '" & Replace(employee_idLabel.Text, "'", "''") & "','" & Replace(dedval.SelectedValue, "'", "''") & "','" & Replace(chckval.Text, "'", "''") & "','" & Replace(chcknumval.Text, "'", "''") & "','" & Replace(onetimeval.Text, "'", "''") & "','" & multival.Text & "','" & Replace(cashval, "'", "''") & "','" & Replace(donatechoice.SelectedItem.Value, "'", "''") & "','" & Replace(datestamp, "'", "''") & "');"
答案 0 :(得分:2)
请查看将ID列设为IDENTITY列。这将自动为每一行分配一个递增的id,你不必自己担心(即你甚至不需要在insert语句中指定列)。
e.g。
CREATE TABLE Example
(
ID INTEGER IDENTITY(1,1),
employee_id INTEGER
)
INSERT Example (employee_id) VALUES (2516) -- Gets ID=1
INSERT Example (employee_id) VALUES (2516) -- Gets ID=2
尝试自己维持递增ID可能会在痛苦的世界中结束,尤其是当多个用户同时尝试插入时。
答案 1 :(得分:1)
这是您的业务逻辑。 我会向你推荐以下结构
create table myTable (
int UserId not null,
int myTableId int identity(1,1) primary key,
int UserSequence int not null
)
并插入这样的语句。
insert into myTable (UserId, UserSequence) values
(10, (select isNull(max(UserSequence), 0) + 1 from myTable where UserId=10))
它完全符合您的需要。您保留主键,但添加另一个用于业务逻辑的列。
修改
顺便说一下,你的VB.Code看起来非常麻烦。
使用ORM,您的代码看起来就像这样。
Dim dc As New MyDatabaseContext
Dim records = dc.Recors.Where(Function(x) x.UserId = 10)
Dim last as Integer = 0
If records.Count > 0 Then last = records.Max(Function(x) x.UserSequence)
Dim instance As New Record With {
.UserId = 10,
.UserSequence = last + 1
}
dc.Records.Add(instance)
dc.SaveChanges()
答案 2 :(得分:0)
这段代码不安全,如果在SELECT和INSERT之间执行另一个进程怎么办?你可以用SQL实现同样的目标:
INSERT INTO table EMP (ID, ...) VALUES ( (SELECT MAX(ID)+1 FROM EMP), ...);
当然,如果您可以使用自动增量/序列字段,则无需担心ID。