Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update Top 1 record in table sql server [duplicate]

My Query

UPDATE TOP (1) TX_Master_PCBA   SET TIMESTAMP2 = '2013-12-12 15:40:31.593' WHERE SERIAL_NO IN ('0500030309')  ORDER BY TIMESTAMP2 DESC  

with serial_No Column in TX_Master_PCBA table i have 10 records but i want to update the latest TIMESTAMP2 to current datetime.

the above query is throwing error :

Incorrect syntax near the keyword 'TOP'.

like image 778
Kapil Avatar asked Dec 12 '13 09:12

Kapil


People also ask

How do I change a large number of rows in SQL?

DECLARE @Rows INT, @BatchSize INT; -- keep below 5000 to be safe SET @BatchSize = 2000; SET @Rows = @BatchSize; -- initialize just to enter the loop BEGIN TRY WHILE (@Rows = @BatchSize) BEGIN UPDATE TOP (@BatchSize) tab SET tab. Value = 'abc1' FROM TableName tab WHERE tab. Parameter1 = 'abc' AND tab.

Can we use top in update statement?

Without the TOP clause, if you are doing a manual update and your mouse text selection only selects from "UPDATE" to just before the "WHERE" clause, then the update is applied to ALL rows. With the TOP clause, only one row would get the undesired update.


1 Answers

WITH UpdateList_view AS (   SELECT TOP 1  * from TX_Master_PCBA    WHERE SERIAL_NO IN ('0500030309')    ORDER BY TIMESTAMP2 DESC  )  update UpdateList_view  set TIMESTAMP2 = '2013-12-12 15:40:31.593' 
like image 162
Bobi Avatar answered Sep 25 '22 04:09

Bobi