views:

31

answers:

2

Can someone please convert this access sql function for me to work in t-sql 2005.

I am tring to take the selling price minus the cost as one number. And divide that by the original selling price to produce a second number

Thanks :)

 =IIf([Selling Price]=0,0,([Selling Price]-Nz([Cost]))/[Selling Price])

IIRC it should be something along the lines of;

ISNULL((ISNULL([Selling Price],0) - ISNULL(Cost,0)),0) / ISNULL([Selling Price],0) AS Margin

But here I am getting a divide by Zero error.

any suggestions?

+1  A: 
CASE 
   WHEN ISNULL([Selling Price], 0) = 0 THEN 0
   ELSE ([Selling Price] - ISNULL([Cost], 0)) / [Selling Price] 
END
Mitch Wheat
Up voted as its very good, thanks :)
Pace
+2  A: 
SELECT
    CASE 
        WHEN ISNULL([Selling Price],0) = 0 THEN 0
        ELSE ([Selling Price] - ISNULL([Cost],0))/[Selling Price]
    END AS fieldName
FROM TableName
Justin Niessner
accepted as most elegant and easy to understand. Thanks very much. I think this was the first. Cheers everyone else :)
Pace
it wasn't quite the first ;) but nice one anyway.
Mitch Wheat
WHEN [Selling Price] IS NULL THEN 0 -- reads a little nicer
Andrew
@Andrew - It may read a little nicer, but it doesn't cover the situation where [Selling Price] = 0
Justin Niessner
Oops - right you are. More coffee for me, please!
Andrew