tags:

views:

3183

answers:

4

I am trying to update a column in table a based on whether a different column in the table is in a set of results from table b. Currently variations on:

update a
set a.field1 =
 case
 when exists (
   select b.field2
   from b
   where b.field2 = a.field2
 )
 then 'FOO'
 else 'BAR'
 end

are not running. Any ideas how to do this for a DB2 database?

Edit: Thanks for your answers, best I can do is

update a set field1 = 'FOO' where field2 in (select field2 from b);

update a set field1 = 'BAR' where field2 not in (select field2 from b);

But I'll leave this open in case someone can find a version of the code at the top that works.

+3  A: 

This works in SQLServer. Perhaps DB2 has a similar construction.

update a SET field1 = 'BAR'
from a
     left outer join b on b.field1 = a.field1
where b.field1 is null;
update a SET field1 = 'FOO'
from a
     inner join b on b.field1 = a.field1

Regards,
Lieven

Lieven
Wow... holy unnecessary updates Batman!
Tom H.
@Tom. This should fix it.
Lieven
That will do the trick. You could still put it into one update statement with a CASE statement checking for NULLs in the PK of table B, but there can also be advantages of doing it in two steps and what you have now eliminates the duplicate updates.
Tom H.
@Tom. My gut feeling tells me that the two updates could be faster than using a case in one update.
Lieven
Syntax doesn't seem to work in DB2, but you're correct in that the spirit of just doing it in two separate runs is clearer.
nearly_lunchtime
Valid syntax (ie DB2 doesn't like updating joins) isupdate a set field1 = 'FOO'where field2 in (select field2 from b);update a set field1 = 'BAR'where field2 not in (select field2 from b);I'll accept if you mention that!
nearly_lunchtime
@Nearly_lunchtime. What would you like me mentioned? You've found the solution yourself. You can answer your own question and accept that? Thank you for suggesting it though.
Lieven
A: 

The first occurence of a.field1 should be a.field2.

You said "whether a different column in the table is in a set..."

Your code is modifying the same column, not a different column.

Walter Mitty
A: 

I'm not an expert on SQL or DB2 but maybe you can join the two tables and check wheither b.field1 is null??

update a set a.field1 = case when b.field1 is not null then 'FOO' else 'BAR' end from a full outer join b on a.field1 = b.field1

Good luck

You probably want to use a LEFT OUTER JOIN rather than a FULL OUTER JOIN
Tom H.
+5  A: 

I work on a DB2 for iSeries box; Try this:

update a set a.field1 = Coalesce( ( select 'FOO' from b where b.field2 = a.field2 ), 'BAR' )

Coalesce() is a function that returns the first non NULL in the list.

Lynette Duffy