Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Update Rows based on previous row

Author  Topic 

sg2255551
Constraint Violating Yak Guru

274 Posts

Posted - 2012-07-12 : 05:46:34
how do i update current row based on previous row? Thanks a lot

The sample
PriCol ColA ColB
1 1 2
2 1
3 1 5
4 1
5 2 1
6 2
7 2 3


The result
PriCol ColA ColB
1 1 2
2 1 2
3 1 5
4 1 5
5 2 1
6 2 1
7 2 3

lionofdezert
Aged Yak Warrior

885 Posts

Posted - 2012-07-12 : 06:54:02
CREATE TABLE #UpdateAsPrevious (PriCol INT, ColA INT, ColB INT)

INSERT INTO #UpdateAsPrevious
SELECT 1, 1, 2 UNION ALL
SELECT 2, 1, NULL UNION ALL
SELECT 3, 1, 5 UNION ALL
SELECT 4, 1, NULL UNION ALL
SELECT 5, 2, 1 UNION ALL
SELECT 6, 2, NULL UNION ALL
SELECT 7, 2, 3


SELECT PriCol,ColA,
ISNULL(ColB,( SELECT TOP ( 1 )
ColB
FROM #UpdateAsPrevious
WHERE PriCol < OuterTable.PriCol
AND ColB IS NOT NULL
ORDER BY PriCol DESC
)) AS ColB
FROM #UpdateAsPrevious OuterTable
ORDER BY PriCol


DROP TABLE #UpdateAsPrevious

--------------------------
http://connectsql.blogspot.com/
Go to Top of Page

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2012-07-12 : 06:55:13
something like this if PriCol has no gaps.
update a
set ColB = b.ColB
from YourTable as a
join YourTable as b on a.PriCol=b.PriCol-1
where a.ColB is null


No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page

sg2255551
Constraint Violating Yak Guru

274 Posts

Posted - 2012-07-12 : 08:48:12
thanks a lot
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-07-12 : 09:48:57
Will PriceCol be having continuos values always without gaps?

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -