SQL Server(T-sql) Update table from botom to top

197 views Asked by At

im trying to update table temp(F4) result from bottom to top. Is it while-loop every row and update can be order by?

enter image description here

Thanks!

1

There are 1 answers

3
Martin Smith On BEST ANSWER

Assuming ROW is a positive integer then you can use (demo)

WITH T1 AS
(
SELECT *, 
       MIN(CASE WHEN F4 <> 0 THEN CONCAT(FORMAT([ROW],'D10'),[F4]) END) 
         OVER (ORDER BY [ROW] ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) AS M
FROM temp

)
SELECT *, 
       CAST(SUBSTRING(M,11,11) AS INT) AS val
FROM T1
ORDER BY [ROW]

If you want to update F4 you can use

WITH T1 AS
(
SELECT *, 
      MIN(CASE WHEN F4 <> 0 THEN CONCAT(FORMAT([ROW],'D10'),[F4]) END) 
           OVER (ORDER BY [ROW] ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) AS M
FROM temp

)
UPDATE T1
SET F4 = COALESCE(SUBSTRING(M,11,11),0);