Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the ID of inserted item [duplicate]

Tags:

c#

sql

sql-server

So I have a query as such:

cmd.CommandText = @"INSERT INTO [dbo].[bill](bruto, waiterid, reversalid, number, ddate, tableid, total, printed, posplace, guestid, numberofguests, closedtime, methodofpaymentid, realdate) " +
                    "VALUES (@bruto, @waiterid, 0, 0, @ddate, 1, @total, 'True', 0, 0, 0, @closedtime, @methodofpaymentid, @realtime) " +
                    "SELECT id";
//+ lines of cmd.Parameter.AddWithValue(...,...);

But once I try to execute the query with:

int newId = Convert.ToInt64(cmd.ExecuteScalar());

I get that id is not identified (even though it Does exist).

If I try changing the SELECT to [dbo].[bill].id, I get the error

The multi-part identifier "dbo.bill.id" could not be bound.

I also tried making it SELECT MAX(id) (as this is the closest thing to a scalar), but yet again, I get the unidentified error.

Thanks for reading.

like image 384
NemanjaT Avatar asked Mar 15 '23 23:03

NemanjaT


1 Answers

You can use the

SELECT SCOPE_IDENTITY()

just after your insert query and it will give you the identity of the last insert row. Check the MSDN for details on SCOPE_IDENTITY().

Returns the last identity value inserted into an identity column in the same scope.

like image 82
Rahul Tripathi Avatar answered Mar 17 '23 16:03

Rahul Tripathi