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

旧城冷巷雨未停 提交于 2021-02-11 04:53:30

问题


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

Thanks!


回答1:


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);


来源:https://stackoverflow.com/questions/41208345/sql-servert-sql-update-table-from-botom-to-top

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!