-1

I am trying to select the ID of the last inserted value on my database in SQL Server. I tried many ways for example @@IDENTITY, IDENT_CURRENT('TableName'), SCOPE_IDENTITY() but nothing was possible. Also I had tried to order by but nothing worked for me.

In my code I have

Select top(1)* 
from Ferramenta_Limpeza 
where Ferramenta_ID!='' and (Id_Gestao between'1' and '434')
order by Id_Gestao desc

My logic was to find the value that is diferent of empty, between 1 and 434. The problem is that this, show always the last value even if I insert another record on 'ID =1', this means that I tryed to update the value of Id 1 and when I tryed the same select to show the las value iserted or updated, the code just show me the last row

Can Someone explain how to do it?

Barbaros Özhan
  • 59,113
  • 10
  • 31
  • 55
Joelson26
  • 1
  • 3

1 Answers1

0

When using the @@IDENTITY, IDENT_CURRENT('TableName'), SCOPE_IDENTITY() you must have a column having a IDENTITY increment value.

Ex : Create the temp table

 CREATE TABLE #TableName
 (
   ID [int] IDENTITY(1,1),
   Name_value VARCHAR(100)
 )

-- execute the insert and this will give you the last inserted value

 insert into #TableName (Name_value) values ('test1')
 insert into #TableName (Name_value) values ('test2')
 insert into #TableName (Name_value) values ('test3')

 select SCOPE_IDENTITY()

Make sure that you read the following link and understand the difference of the output

What is the difference between Scope_Identity(), Identity(), @@Identity, and Ident_Current()?

  • *you should have an identity column* - no, not you **should** - you ***MUST HAVE*** an identity column. – marc_s Jul 10 '19 at 20:26