问题
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