使用身份是迄今为止最好的主意。我像这样创建所有表:
CREATE TABLE mytable (
mytable_id int identity(1, 1) not null primary key,
name varchar(50)
)
“身份”标志的意思是“让 SQL Server 为我分配这个号码”。(1, 1) 表示身份编号应从 1 开始,每次有人将记录插入表中时递增 1。Not Null 意味着不允许任何人在该列中插入空值,而“主键”意味着我们应该在该列上创建聚集索引。使用这种表格,您可以像这样插入记录:
-- We don't need to insert into mytable_id column; SQL Server does it for us!
INSERT INTO mytable (name) VALUES ('Bob Roberts')
但是要回答您的字面问题,我可以上一堂有关交易如何运作的课程。这样做当然是可能的,尽管不是最佳的:
-- Begin a transaction - this means everything within this region will be
-- executed atomically, meaning that nothing else can interfere.
BEGIN TRANSACTION
DECLARE @id bigint
-- Retrieves the maximum order number from the table
SELECT @id = MAX(order_number) FROM order_table
-- While you are in this transaction, no other queries can change the order table,
-- so this insert statement is guaranteed to succeed
INSERT INTO order_table (order_number) VALUES (@id + 1)
-- Committing the transaction releases your lock and allows other programs
-- to work on the order table
COMMIT TRANSACTION
请记住,使用标识主键列声明您的表会自动为您完成这一切。