Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use row_number() in SQL Server

I want to update row data where the row_number of the column (p_id) is 1.. but this syntax is providing error:

update app1 
set p_id = 1 
where Row_Number() = 1 over(p_id) 
like image 958
user635545 Avatar asked Feb 24 '23 12:02

user635545


1 Answers

You can't use ROW_NUMBER() directly - you need to e.g. use a CTE (Common Table Expression) for that:

;WITH DataToUpdate AS
(
    SELECT
       SomeID,
       p_id,
       ROW_NUMBER() OVER(ORDER BY .......) AS 'RowNum'
    FROM
       dbo.app1
)
UPDATE DataToUpdate
SET p_id = 1
WHERE 
   RowNum = 1

In order to use the ROW_NUMBER function, you also need at least an ORDER BY clause to define an order by which the rows are ordered.

From your question, it's not very clear what criteria (column) you want to order by to determine your ROW_NUMBER(), and it's also not clear what kind of column there is to uniquely identify a row (so that the UPDATE can be applied)

like image 172
marc_s Avatar answered Feb 27 '23 05:02

marc_s