views:

336

answers:

3

I've written this function before but I can't seem to remember it and it didn't get into version control. Now, more to do with sleep deprivation than anything else, I can't remember how to rebuild it.

Here's the idea. I have two tables, "regPrice" and "custPrice", with shared key "itemID." They both have a "price" column and custPrice also has another key "acct" such that if a price exists in custPrice, it should return that one. If there isn't a custPrice entry, it should return the regPrice.

pseudoCode:

if(select custPrice where acct = passedAcct and itemID = passedItemID) {
   return custPrice;
else 
   return regPrice;

Any help would be appreciated.

+1  A: 

Look into the COALESCE function, unless you're not using NULL, in which case you'll want to use a CASE.

orthod0ks
Sounds like sql server- he asked for mysql
Joel Coehoorn
+6  A: 
SELECT COALESCE(c.price, r.price) AS price
FROM regPrice r LEFT OUTER JOIN custPrice c
 ON (r.itemID = c.itemID AND c.acct = ?)
WHERE r.itemID = ?;
Bill Karwin
Looks good. To make it a stored procedure it would just be: CREATE PROCEDURE pricing (I_itemID INT, I_acct INT) SELECT COALESCE(c.price, r.price) AS priceFROM regPrice r LEFT OUTER JOIN custPrice c ON (r.itemID = c.itemID AND c.acct = I_acct)WHERE r.itemID = I_itemID;Is this correct?
Drew
Yes that procedure works fine.
Bill Karwin
+2  A: 
select r.itemID, r.Acct,
case when c.price is null then r.price else c.price end as price
from regPrice r
left outer join custPrice c
on r.itemID = c.itemID
and r.Acct = @passedAcct
where r.itemID = @passedItemID
Gordon Bell
Is there a performance difference between a CASE or a COALESCE?
Drew
No, there shouldn't be.
Gordon Bell