Reputation: 353
I want to insert a row and return the identity column value from a procedure! For this I dont want to use any advanced things like @@identity
or SCOPE_IDENTITY
etc as I don't have a clear picture about how they work.
So I am planning to do this
I am familiar with oracle lock
lock table tab1 in exclusive mode;
INSERT INTO tab1.....;
select max(id) into retVal from tab1;
Questions:
Upvotes: 0
Views: 274
Reputation: 1674
You'll be creating more problems than solving by forcing locks on your database/tables. Let the Database Management System (DBMS) manage the database.
All you need to do is:
BEGIN TRANSACTION --added after original answer
INSERT INTO tab1....;
SELECT @@identity AS [last_id] INTO retVal;
END TRANSACTION --added after original answer
I trust you know that you can only SELECT...INTO retVal
so long as the retVal
table doesn't already exist.
Upvotes: 1
Reputation: 559
which version of sql server it is?
If you are running sql server 2008+ (r2 i thing)
The safest way is to use the output statement of an insert.
Like this :
insert into Customer (Name, Address, Phone) output inserted.CustomerId into @CustomerId values (......)
Upvotes: 2