sql server 2008 - Updating a column based on 3 tables and 2 rules -
i have 3 tables follows:
declare @tablea table (id int, name varchar(2)); declare @tableb table (name varchar(2)); declare @tablec table (id int, name varchar(2)) insert @tablea(id, name) select 01, 'a4' union select 01, 'sh' union select 01, '9k' union select 02, 'm1' union select 02, 'l4' union select 03, '2g' union select 03, '99'; insert @tableb(name) select '5g' union select 'u8' union select '02' union select '45' union select '23' union select 'j7' union select '99' union select '9f' union select 'a4' union select 'h2'; insert @tablec(id) select 01 union select 01 union select 01 union select 02 union select 02 union select 03 union select 03;
basically, @tablec.id populated @tablea.id (same rows)
now, have populate @tablec.name considering following rules:
it should values @tableb.name , provided same @tablea.name should not exists same id in @tablea. id = 1, @tablec.name should values a4, sh, 9k.
@tablec.name should distinct each @tablec.id. @tablec.name should not have 2 same values same id have same @tablec.name different ids.
the query using solve rule#1 : (please edit apply rule #2)
update c set name = (select top 1 b.name @tableb b b.name not in (select name @tablea a.id = c.id) order newid() ) @tablec c select * @tablec
clean @tablec before executing code above:
declare @tabled table (id int, name varchar(2)) insert @tabled select distinct * @tablec delete @tablec insert @tablec select * @tabled update c set name = (select top 1 b.name @tableb b b.name not in (select name @tablea a.id = c.id) order newid() ) @tablec c select * @tablec
there may more graceful way of doing this, quick way if not lot of rows in @tablec.
Comments
Post a Comment