Click here to Skip to main content
15,893,337 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have table called

table:ITEMS
fields:itemid->pk
address
location
title



CATEGORY
catid->pk
categoryname


CATEGORY_VALUE
catvalid->pk
itemid->fk (ITEMS)
catid->fk (CATEGORY)
catval

i insert data into items table and category table is filled with predefined values which can be increased later on.

now when i insert data in items table i also have to insert data in category_value table.

I can implement this using MAX function on ID of items table then again execute insert query on category_value table

but i want to use stored procedure which completely performs this task.


is there a direct function in sql server which can fetch the latest inserted record and store it in some local variable and then i can write insert query
.
Posted

No, MAX and such things might mislead you in production environments since there is also something called transaction. If your primary keys are identities[^], you can use SCOPE_IDENTITY[^] and IDENT_CURRENT[^] to get the latest identity generated on a table or in a scope. You probably will need the scope version, since the procedure execution is not atomic.
Read this short article: http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/[^].

If your primary keys are not identity fields, than you will have to use locks and other fancy things - which I don't recommend.

In SQL Server 2012 there is at last implemented the SEQUENCE[^] object, which is part of the SQL standard for a very long time...
 
Share this answer
 
Comments
gaurish thakkar 27-Oct-12 8:26am    
thnks for the advice.All my pk fields are identity fields. can i store the scopeidentity value in a var and use it for my insert statement.?
Zoltán Zörgő 27-Oct-12 8:31am    
Of course.
Like this:

DECLARE @newid int;
SET @newid = (SELECT IDENT_CURRENT('tablename'));
or
DECLARE @newid int;
SET @newid = (SELECT SCOPE_IDENTITY());
respectively.
gaurish thakkar 27-Oct-12 14:49pm    
Thank u
Dear sir is there a way to pass multiple values in a single parameter .

for example passing an array-list for a sql server parameter.so that it can be accessed in stored procedure
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900