Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL How to update the bottom/last row only?

I want to update the bottom/the last row in my table. I have try to implement this solution, but nothing seems as correct syntax:

UPDATE TOP(1) @ResultTable
SET PeriodLastDate=DATEADD(DAY,-1,PeriodLastDate)
ORDER BY PeriodID DESC

OR

UPDATE TOP(1) @ResultTable
SET PeriodLastDate=DATEADD(DAY,-1,PeriodLastDate)
FROM @ResultTable
ORDER BY PeriodID DESC

What I have till now working is:

UPDATE @ResultTable
SET PeriodLastDate=DATEADD(DAY,-1,PeriodLastDate)
WHERE PeriodID=(SELECT COUNT(PeriodID) FROM @ResultTable)-1

but this will not always works, as in my function some of the records are deleted and I am not always having PeriodIDs incremented with 1.

like image 596
gotqn Avatar asked Nov 08 '12 16:11

gotqn


1 Answers

What about :

UPDATE ResultTable SET PeriodLastDate='NewValue' WHERE ID= (SELECT MAX(ID) FROM ResultTable)
like image 66
Laurent Avatar answered Oct 06 '22 00:10

Laurent