6

In SQL Server 2008, I have a set of data containing costs for East and West. I'm adding a new field for a customer for Canada which needs to be 1.5 times the East or West cost (which ever is greater). So I'm trying to come up with some sql I can execute. I've tried the following but have not had success:

 UPDATE ShippingCost

 SET

    IF EastCost>WestCost

       Canada= EastCost*1.8

    ELSE

       Canada= WestCost*1.8
    ENDIF

I'm sure there's an easy way to do this? Any ideas?

3
  • Could you please specify what database platform you're working with? Commented Jan 25, 2012 at 16:59
  • Using MS SQL Server 2008 Commented Jan 25, 2012 at 17:02
  • Your spec says, "1.5 times the East or West cost (which ever is greater)" i.e. factor is 1.5 but your code uses the factor 1.8. Commented Jan 26, 2012 at 11:17

4 Answers 4

17

You need to use Case

 UPDATE ShippingCost

 SET
     Canada = CASE WHEN EastCost>WestCost THEN  EastCost*1.8
                   ELSE WestCost*1.8 END
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent! Works exactly the way I want. Thanks!
0

Use two update statements:

UPDATE SHIPPINGCOST SET Canada = EastCost*1.8 WHERE EastCost>WestCost
UPDATE SHIPPINGCOST SET Canada = WestCost*1.8 WHERE EastCost<=WestCost 

1 Comment

Performance. If the table is large then the optimizer might not be smart enough to exploit an index if you use the CASE statement. Also, not sure how portable the CASE clause is. I know it wasn't supported in some older Oracle versions (you had to use DECODE). It's ANSI standard now, but you still have to make sure it works in the version of the DB you are running.
0
UPDATE ShippingCost
   SET Canada = 1.5 * CASE 
                         WHEN EastCost > WestCost THEN EastCost
                         ELSE WestCost
                      END;

Comments

0
 UPDATE ShippingCost SET Canada = GREATEST(EastCoast, WestCoast) * 1.8;

Note: T-SQL dialect does not support GREATEST.

2 Comments

MySQL and Oracle have GREATEST but I can't think of any Dialect that does Max(a,b)
Yes, it's not MAX but GREATEST. Sorry for the mistake! MAX is another function that doesn't work in this case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.