Microsoft
Software
Hardware
Network
Question : Return the ID of a newly inserted record
I need to find out which ID a newly inserted Record has been assigned by the Database Server. Doing this using 'select max(fieldname) from table' after Insert or 'select max(fieldname)+1 from table' before Insert may be too unsecure; I need a 100% working solution, even if others are working on the database. What can I do?
Answer : Return the ID of a newly inserted record
here is one af many wais:
the insert should be enclosed in a stored procedure.
definiton of table should include
create table
(
...
[ID] int identity( 1,1 )
...
)
where int, numeric, decimal, or bigint ( bigint works for SQL Server 2000 only ) is the data type
and body of the stored procedure should protect insert in a transaction, and following the transaction in case of success an identity value can be retrieved this way for SQl Server 7
SELECT @my_variable = @@identity
SQl Server 2000
SELECT @my_variable = IDENT_CURRENT( '
' )
at
a more complete exerpt from stored procedure bidy's code may look like this
create procedure ms_insert_with_return_reco
rd_id
@values_to_insert_1 int
, ...
, @record_id int = 0 OUT
AS
BEGIN TRANSACTION
insert into t
(
colunm_1
, ...
)
select
@values_to_insert_1
,
SELECT @record_id = @@identity
IF @@error <> 0
BEGIN
ROLLBACK TRANSACTION
SELECT @record_id = 0
return (1) -- error occurred
END
ELSE
COMMIT TRANSACTION
return (0) -- no error
Make sure that no value is inserted into the column that is defined as identity. IT will be generated for you, according to the definition at the moment when you created table: identity( 1, 1 ) means start from 1 and add 1 to each new number, identity ( 1, 5 ) means start from 1 and add 5 to each new generated number, as you can see identity follows this definition
identity ( seed, increment )
Random Solutions
How to delete similar files with python?
Event ID: 1505 - insufficient system resources exist to complete the requested service
Check if FTP upload was successful
Restrict outgoing email for certain users
input dd/mm/yyyy date format in MSAccess entered as mm/dd/yyyy how to avoid?
Example logon and logoff script to change enableproxy setting
Microsoft Access Open Email Message (Outlook) and populate it with data from the database!
delete message on exchange server with out remove mailbox or user account
event listener for error with loader?
Resize Ghost Image