Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Select or Insert return ID

Alright so a quick SQL question here(using sql-server-2008).

I have a mapping table names with the following columns

ID DisplayName

What I want to do is first SELECT [ID] FROM [names] WHERE [DisplayName] = 'chuck';

BUT, if the name 'chuck' doesn't exist in the database, I would like to create it, and return the auto incremented ID.

I was wondering if SQL had some built in way of doing this in an easy way, or if I have to go the long route?

long route being something like this

SELECT COUNT(ID) AS count, ID FROM names WHERE DisplayName='chuck'
IF(count > 0)
    SELECT ID as ReturnID;
ELSE
    BEGIN
    INSERT INTO names(DisplayName) values('chuck');
    SELECT scope_identity() as ReturnID;
    END

I didn't test that last statement, but I assume the long way would be something like that. If there is no built in way, I'd appreciate it if someone could simply correct that statement(as I'm sure it isn't completely correct).

like image 720
Kelly Elton Avatar asked Feb 26 '12 22:02

Kelly Elton


People also ask

How do I return a insert ID in SQL?

We use SCOPE_IDENTITY() function to return the last IDENTITY value in a table under the current scope. A scope can be a module, trigger, function or a stored procedure. We can consider SQL SCOPE_IDENTITY() function similar to the @@IDENTITY function, but it is limited to a specific scope.

How do I get my identity back after insert?

The @@Identity function will return the last identity value inserted in the current session, in any table and in any scope. The Scope_Identity() function will return the last identity value inserted in the current scope (and session), in any table.

What does insert query return?

An SQL INSERT statement writes new rows of data into a table. If the INSERT activity is successful, it returns the number of rows inserted into the table.

What is inserted ID in SQL?

IDENT_CURRENT(tablename) is the last identity inserted regardless of connection or scope. You could use this if you want to get the current IDENTITY value for a table that you have not inserted a record into.


1 Answers

You should take care about transactions as well:

set XACT_ABORT on
begin tran

declare @ID int

select @ID = ID from names with (holdlock, updlock) WHERE DisplayName='chuck'

if @@rowcount = 0
begin
  INSERT INTO names(DisplayName) values('chuck');
  set @ID = scope_identity();
end

select @ID as ReturnID;

commit tran

Note the usage of table hints - holdlock and updlock. They prevent another thread from executing exactly the same query and creating the row a second time. For more information look for isolation, synchronization, deadlocks, concurrent updates.

like image 152
Coder Avatar answered Oct 15 '22 08:10

Coder