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
 General SQL Server Forums
 New to SQL Server Programming
 Help with Update statment

Author  Topic 

slihp
Yak Posting Veteran

61 Posts

Posted - 2014-06-16 : 14:40:04

Hi there

im not sure how to do this as im not great with update statements. I have a table that get populated with related ids. basically i want to periodicaly update the table and set the related ids to the last know id that was entered, so in the case below

this set

ID | LinkID | Active | Date
z5 | k2 | 0 | 01/01
s6 | k2 | 0 | 17/02
d7 | k2 | 0 | 21/03
d8 | k2 | 0 | 20/04
d9 | k2 | 1 | 02/05

would be updated to this

ID | LinkID | Active | Date
d9 | k2 | 0 | 01/01
d9 | k2 | 0 | 17/02
d9 | k2 | 0 | 21/03
d9 | k2 | 0 | 20/04
d9 | k2 | 1 | 02/05

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2014-06-16 : 15:06:55
[code]
--create table/sample data
create table #temp (ID char(2), LinkID char(2), Active bit, [Date] datetime)
insert into #temp values ('z5', 'k2', 0, '01/01/14')
insert into #temp values ('s6', 'k2', 0, '02/17/14')
insert into #temp values ('d7', 'k2', 0, '03/21/14')
insert into #temp values ('d8', 'k2', 0, '04/20/14')
insert into #temp values ('d9', 'k2', 1, '05/02/14')
insert into #temp values ('a4', 'k9', 0, '01/01/14')
insert into #temp values ('z8', 'k9', 1, '05/17/14')

--the part you care about
;with cte1 (LinkID, [Date])
as
(
select LinkID, max([Date])
from #temp
group by LinkID
),
cte2 (ID, LinkID, [Date])
as
(
select t.ID, cte1.LinkID, t.[Date]
from #temp t
join cte1
on t.LinkID = cte1.LinkID and t.[Date] = cte1.[Date]
)
update t
set ID = cte2.ID
from #temp t
join cte2 on t.LinkID = cte2.LinkID and t.[Date] <> cte2.[Date]

--validate update
select * from #temp

--cleanup
drop ttable #temp
[/code]

Tara Kizer
SQL Server MVP since 2007
http://weblogs.sqlteam.com/tarad/
Go to Top of Page
   

- Advertisement -