SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Update Rows based on previous row
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

sg2255551
Constraint Violating Yak Guru

250 Posts

Posted - 07/12/2012 :  05:46:34  Show Profile  Reply with Quote
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

Pakistan
864 Posts

Posted - 07/12/2012 :  06:54:02  Show Profile  Visit lionofdezert's Homepage  Send lionofdezert a Yahoo! Message  Reply with Quote
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/

Edited by - lionofdezert on 07/12/2012 07:07:34
Go to Top of Page

webfred
Flowing Fount of Yak Knowledge

Germany
8513 Posts

Posted - 07/12/2012 :  06:55:13  Show Profile  Visit webfred's Homepage  Reply with Quote
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

250 Posts

Posted - 07/12/2012 :  08:48:12  Show Profile  Reply with Quote
thanks a lot
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
47023 Posts

Posted - 07/12/2012 :  09:48:57  Show Profile  Reply with Quote
Will PriceCol be having continuos values always without gaps?

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

Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.05 seconds. Powered By: Snitz Forums 2000