sqlsql-serversql-update

How to update only one row in a table?


How to I can update only one record in a table?

Table:

name       name1       name2
----------------------------
xx         xy          xz
xx         xx          xx
xx         xx          xx
xx         xx          xx
xy         xx          zz

Update query:

UPDATE table1 
SET name2 = '01' 
WHERE name1='xx'

I need update only one row per time.


Solution

  • You can use UPDATE TOP (n) (note the required parentheses!):

    UPDATE TOP (1) table1 
    SET name2 = '01' 
    WHERE name1 = 'xx'
    

    You can also use SET ROWCOUNT n, though this is deprecated for UPDATE, DELETE, & INSERT statements, and will stop functioning in a future SQL Server version.

    SET ROWCOUNT 1
       
    UPDATE table1 
    SET name2 = '01' 
    WHERE name1 = 'xx'
        
    SET ROWCOUNT 0