or you can use: select max(id) + 1
And what happens if you and another person both get the same value at the same time? This doesn't work.
anon47,
Perhaps you need two tables with a 1-to-0-or-1 relationship.
In the "left" table you include all columns that are required before an insert can be made. In the "right" table you put everything else, with a clustered foreign key to the id column of the other table.
Now you can insert to the left table, get an ID, then wait for user input. When you're done, you can insert using the known ID to the right table. The right table can then have NOT NULL and CHECK constraints and things that you otherwise couldn't have with the single-table approach.
If that sounds like a lot of work, then maybe you could figure out how to avoid needing the user id until after record creation, as was already suggested by Phil.
A final option is not so much a left and a right table but to manage the incrementing number value yourself (I don't like this but it works):
Code:
CREATE TABLE NextUserID (UserID int)
INSERT NextUserID VALUES (1)
GO
CREATE PROC GetNextUserID @NextUserID int OUTPUT
AS
UPDATE NextUserID
SET @NextUserID = UserID, UserID = UserID + 1
GO
DECLARE @UID int
EXEC GetNextUserID @UID OUTPUT
SELECT [Your new userid is] = @UID
Since the work is done in a single update statement, there is no risk of multiple people getting the same value. This is less efficient than an identity column (by far) and does block while the update is being performed.
[COLOR=black #e0e0e0]For SQL and technical ideas, visit my blog,
Squared Thoughts.
The best part about anything that has cheese is the cheese.[/color]