Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SCOPE_IDENTITY() not working

When I try to get the last ID inserted on Database via SQL Server it returns __Page. Here is my code :

query = "INSERT INTO
             seekers(name, sname, lname, status, gender, dob, major, experince,
                     email, password, phone, valid, city)
             values (@name, @sname, @lname, @status ,@gender, @dob, @major,
                     @exp, @email, @password, @phone, 0, @city);
         SELECT SCOPE_IDENTITY();";

// some code here related to parameters

command = new SqlCommand(query, connection);
int id = Convert.ToInt32(command.ExecuteScalar());
like image 870
Hatem Avatar asked Sep 20 '12 08:09

Hatem


People also ask

What is SCOPE_IDENTITY () in SQL Server?

SCOPE_IDENTITY() returns the IDENTITY value inserted in T1. This was the last insert that occurred in the same scope. The SCOPE_IDENTITY() function returns the null value if the function is invoked before any INSERT statements into an identity column occur in the scope.

What is SCOPE_IDENTITY in C#?

From the documentation of SCOPE_IDENTITY(), emphasis mine: Returns the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch.

How do I return a insert ID in SQL?

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.


1 Answers

If just you want to SELECT it use OUTPUT;

INSERT INTO seekers(name,sname,lname,status,gender,dob,major,experince,email,password,phone,valid,city)
OUTPUT INSERTED.IDENTITY_COL_NAME
values(@name,@sname,@lname,@status,@gender,@dob,@major,@exp,@email,@password,@phone,0,@city);
like image 92
Alex K. Avatar answered Oct 15 '22 11:10

Alex K.