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
 General SQL Server Forums
 New to SQL Server Programming
 Table column update
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Aksaa
Starting Member

United Arab Emirates
3 Posts

Posted - 02/04/2013 :  00:58:39  Show Profile  Reply with Quote
Hi all,
I have a table with three columns ex.
id,LineNo,Val
1 1 xxx
2 NULL yyy
3 NULL zzz
4 2 ddd
5 NULL ttt
6 NULL uuu
7 3 hhh
8 NULL HYU

i wanted to updated the second column with NULL values with the previous LineNo

expected output:
1 1 xxx
2 1 yyy
3 1 zzz
4 2 ddd
5 2 ttt
6 2 uuu
7 3 hhh
8 3 HYU

Kindly advise me how can i update the same table with query without using cursor.

regards,
Aksaa

visakh16
Very Important crosS Applying yaK Herder

India
52309 Posts

Posted - 02/04/2013 :  01:02:52  Show Profile  Reply with Quote

UPDATE t
SET t.LineNo= t1.PrevLineNo
FROM table t
CROSS APPLY (SELECT MAX(LineNo) AS prevLineNo
             FROM table
             WHERE id < t.id
             AND LineNo IS NOT NULL
             )t1


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

Go to Top of Page

Aksaa
Starting Member

United Arab Emirates
3 Posts

Posted - 02/06/2013 :  05:05:17  Show Profile  Reply with Quote
Hi visakh,

Thanks for the script. with a minor change i was able to get the required output:
final query is:
UPDATE t
SET t.LNo= t1.PrevLineNo
FROM dbo.Header t
CROSS APPLY (SELECT MAX(LNo) AS prevLineNo
FROM dbo.Header
WHERE id < t.id
AND LNo IS NOT NULL
)t1
WHERE t.Lno is null

Thanks once again,
regards
Aksaa
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
52309 Posts

Posted - 02/06/2013 :  11:10:13  Show Profile  Reply with Quote
welcome

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