我有一个网站,我需要用户通过添加他们的细节和提交来注册自己。在提交时,每个用户都应该被分配到递增的唯一ID。为了测试这一点,我让15个用户在网站上输入必要的细节,然后同时点击注册,然而有两组用户得到了相同的ID分配给他们。当所有用户在不同的时间注册时,这并不是一个问题,因为ID的分配是唯一的。
我如何确保每个用户在同时注册时都能得到唯一的ID。
最简单的方法是给每个用户分配一个唯一的ID,要么使用一个 IDENTITY
专栏 表上的ID(如果你想在记录成功写入时分配),或在你的用户表上的一个 SEQUENCE
对象 如果你想获得一个独特的ID 之前 在数据库中创建用户账户。
create table MyUserTable (
UserID int identity(1,1) NOT NULL constraint PK_MyUserTable PRIMARY KEY CLUSTERED
,UserName nvarchar(50)
,Email nvarchar(100);
insert into MyUserTable output inserted.UserId values ('MyUserName', '[email protected]');
将把记录写到表中,并返回创建的ID。
如果你想在写到表中之前取一个ID。
CREATE SEQUENCE UserIds as int start with 1 increment by 1;
create table MyUserTable (
UserID int NOT NULL constraint PK_MyUserTable PRIMARY KEY CLUSTERED
,UserName nvarchar(50)
,Email nvarchar(100);
select next value for UserIds
-- Do whatever you need to do in the application
insert into MyUserTable (UserId,UserName,Email) values (UserIdYouGotEarlier, 'MyUserName','[email protected]');
明白这两种方法都不能保证有连续的ID。在事务回滚的情况下,这些仍然都会自动增加,这些值会 "丢失"。但你首先不应该依赖于它们是顺序的。
你可能也会希望在这些用户名字段上有一个唯一的约束。