Retrieving the ID of an inserted item

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 as soon as I try to execute the request with:

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

I get that the identifier is not identified (although it exists).

If I try to change SELECTto [dbo].[bill].id, I will get an error

An identifier with multiple parts of "dbo.bill.id" cannot be associated.

I also tried to make it SELECT MAX(id)(since this is the closest to the scalar), but again I get an unidentified error.

Thanks for reading.

+4
source share
2 answers

you can use

SELECT SCOPE_IDENTITY()

, . . MSDN SCOPE_IDENTITY().

, .

+7

insert OUTPUT INSERTED. .

:

INSERT .... OUTPUT INSERTED.ID

.

0

All Articles