Posted: 1/31/2012
i have 3 tablestbl_indicatorgrp_nbr sect_nbr indicat1 100 p2 101 stbl_groupgrp_id grp_nbr sect_nbr indicat333 1 100 a555 1 100 p444 2 101 s222 2 101 yhere (in tbl_group) grp_id is P.Ktbl_orderorder_id grp_id5000 3335001 5555002 5555003 5555004 4445005 4445006 222here (in tbl_order) grp_id is F.K to grp_id in tbl_groupnow the thing is that in table tbl_indiactor for one set of grp_nbr and sect_nbr there is an indicat, for the same set of grp_nbr and sect_nbr there is a correct indicat(333,1, 100, p) and a junk indicat(555, 1, 100, a) in table tbl_group.but both these grp_id s(333, 555) are present in table tbl_ordersnow i need to update tbl_order table in such a way that the junk grp_id s should replace with correct grp_id sthe output should liketbl_ordersorder_id grp_id5000 5555001 5555002 5555003 5555004 4445005 4445006 444can some one help me please.....
Posted: 3/26/2012
My first step is to find the values needed in a select. I then use that select as the basis for the update statement.
I think this is what you want.
declare @t_indicator table (grp_nbr smallint, sect_nbr smallint, indicat char(1));declare @t_group table (grp_id smallint, grp_nbr smallint, sect_nbr smallint, indicat char(1));declare @t_order table (order_id int, grp_id smallint);insert into @t_indicator (grp_nbr,sect_nbr,indicat) values (1,100,'p') ,(2,101,'s');insert into @t_group (grp_id,grp_nbr,sect_nbr,indicat) values (333,1,100,'a'),(555,1,100,'p'),(444,2,101,'s'),(222,2,101,'y');insert into @t_order(order_id,grp_id) values (5000,333),(5001,555) ,(5002,555), (5003,555),(5004,444),(5005,444),(5006,222);update o set o.grp_id = qGood.grp_idfrom @t_order ojoin @t_group g on g.grp_id = o.grp_idjoin @t_indicator i on i.grp_nbr = g.grp_nbrjoin ( select g.grp_id,g.grp_nbr,g.sect_nbr,g.indicat from @t_group g join @t_indicator i on i.grp_nbr = g.grp_nbr where g.indicat = i.indicat) qGood on qGood.grp_nbr = g.grp_nbr and qGood.sect_nbr = i.sect_nbr and qGood.indicat = i.indicatwhere g.indicat <> i.indicat---------select * from @t_order