Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
alexjamesbrown
Starting Member
48 Posts |
Posted - 2009-02-27 : 12:34:48
|
| Hi guys,Im trying to create a UDF to calculate Effective cost of a mobile phone contract...Here is my attempt.Basically - heres how it should work.Need to pass in TariffID, to select ContractType, in order to get contract length 1, 12, 18, 24 months etc...The rest is passed in as parameters (it is going to be a computed column on a table which has all these params...)The calculation is-work out the total cost of the contract - this is the line rental multiplyed by number of monthswork out total discount:Work out the value (in money) of months freeWork out the value (in money) of months half priceadd those 2 values together, and add cost offset (cost offset is a negative number)that is then the total discountthen, subtract the total discount, from the total cost, that leaves you with the actual costreturn the actual cost, divided by the number of months.Here is my attempt... it returns 0 or null at the moment...Any ideas?CREATE function dbo.fn_GetEffectiveCost ( @TariffID varchar(50), @MonthsFree smallint, @MonthsHalf smallint, @Cashback money) RETURNS intAS BEGINDeclare @finalResult MONEYDECLARE @LineRental money DECLARE @CostOffset moneyDECLARE @ContractLength intDECLARE @ContractType varchar(3)SELECT @ContractType = ContractType FROM Tariff WHERE TariffID = @TariffIDSELECT @CostOffset = CostOffset FROM Tariff WHERE TariffID = @TariffIDSELECT @ContractLength = REPLACE(ContractType, 'm', '') FROM Tariff WHERE TariffID = @TariffID;DECLARE @TotalCost moneyDECLARE @TotalDiscount money SET @TotalDiscount = ((@LineRental * @MonthsFree) + ((@LineRental / 2)* @MonthsHalf) + @Cashback) - @CostOffsetSET @TotalCost = (@LineRental * @ContractLength) RETURN (@TotalCost-@TotalDiscount)/@ContractLengthEND |
|
|
TG
Master Smack Fu Yak Hacker
6065 Posts |
Posted - 2009-02-27 : 12:39:17
|
| One reason you may be getting NULLs is that if any of the parameters is NULL (ie: no MonthsHalf value) then the entire result will be null. You need to COALESCE these values with the appropriate default value. Also I assume @contractLength has to be greater than 0 but if it can be zero then you will get a devide by zero error.EDIT:looks like @lineRental is not being set anywhere so that will always cause a NULL result.Be One with the OptimizerTG |
 |
|
|
|
|
|
|
|