ID を使用することは、断然最良のアイデアです。次のようにすべてのテーブルを作成します。
CREATE TABLE mytable (
mytable_id int identity(1, 1) not null primary key,
name varchar(50)
)
"identity" フラグは、"SQL Server にこの番号を割り当てさせる" ことを意味します。(1, 1) は、ID 番号が 1 から始まり、誰かがテーブルにレコードを挿入するたびに 1 ずつ増えることを意味します。Not Null は、誰もこの列に 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
ID主キー列を使用してテーブルを宣言すると、これがすべて自動的に行われることに注意してください。