-1

My C# code inserting sqlserverdatabase but how can I access last inserted value? For exp; I have a parameters as a DateTime I assign this parameters 'DateTime.Now' I can access value which in inserted past but I wanna access last inserted value. I mean same code will both insert and get.

Hygieia
  • 11
  • do you have an auto increment rowid in the table? did you try to order by date descending and take the first one? – Mong Zhu Jul 29 '19 at 08:29
  • could you clarify further? last inserted value of the auto increment id column? if yes, you could Scope_Identity or identity depending on your requirments. if the last inserted value of the datetime column, then you will have to retrieve the record and then find the value of the column. – Baahubali Jul 29 '19 at 08:29
  • The question is unclear. The last inserted DateTime value is the one your own code provided - `DateTime.Now`. Are you asking how to access the latest *row*? You'll find many duplicates that show this - it could be a simple `SELECT TOP 1 ... ORDER BY SomeDate desc` – Panagiotis Kanavos Jul 29 '19 at 08:29
  • see this question about [Execute Insert command and return inserted Id in Sql](https://stackoverflow.com/questions/18373461/execute-insert-command-and-return-inserted-id-in-sql) – huMpty duMpty Jul 29 '19 at 08:32
  • If you want to return a value generated on the server like an ID or a calculated field, use the OUTPUT clause in the INSERT statement – Panagiotis Kanavos Jul 29 '19 at 08:33
  • Data is not stored in the SQL server in any particular order. The server is multi-threaded so you must always use a orderby when order is important. So to get latest date you must sort by date in decreasing order and then use TOP (or first/last in linq) to get the latest date. – jdweng Jul 29 '19 at 09:26

1 Answers1

0

Add

OUTPUT INSERTED.COLUMN

In your Query

Marco Salerno
  • 5,131
  • 2
  • 12
  • 32