tsql update (help me)

Who is online?  0 guests and 4 members
Home  »  Forums   »  bidn   »  general bi discussion   » tsql update (help me)

tsql update (help me)

Topic RSS Feed

Posts under the topic: tsql update (help me)

Posted: 1/31/2012

Jedi Youngling 4  points  Jedi Youngling
  • Joined on: 1/31/2012
  • Posts: 2
i have 3 tables

tbl_indicator
grp_nbr sect_nbr indicat
1 100 p
2 101 s


tbl_group
grp_id grp_nbr sect_nbr indicat
333 1 100 a
555 1 100 p
444 2 101 s
222 2 101 y

here (in tbl_group) grp_id is P.K

tbl_order
order_id grp_id
5000 333
5001 555
5002 555
5003 555
5004 444
5005 444
5006 222
here (in tbl_order) grp_id is F.K to grp_id in tbl_group


now 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_orders
now i need to update tbl_order table in such a way that the junk grp_id s should replace with correct grp_id s

the output should like

tbl_orders
order_id grp_id
5000 555
5001 555
5002 555
5003 555
5004 444
5005 444
5006 444

can some one help me please.....

tags SQLBIGeek

Posted: 3/26/2012

Jedi Youngling 18  points  Jedi Youngling
  • Joined on: 4/7/2010
  • Posts: 4

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_id
from @t_order o
join @t_group g on g.grp_id = o.grp_id
join @t_indicator i on i.grp_nbr = g.grp_nbr
join (
    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.indicat
where g.indicat <> i.indicat

---------
select * from @t_order


Page 1 of 1 (2 items)