# Visual Basic > Database Development >  [RESOLVED] SQL Server - help with function please

## MMock

I have to add logic to a function and am having trouble with it.
Here is the original function.


```
CREATE FUNCTION [dbo].[fn_ProfitAndLossCalculateTotalItemSell] 
(
	@SONumber nvarchar(8)
)
RETURNS decimal(9,2)
AS
BEGIN

	DECLARE @Result decimal(9,2)

	SELECT @Result = isnull(SUM((qty_shipped / unit_size) * unit_price * (slmPerc / 100)),0) FROM qryP21_ProductivitySLM WHERE order_no = @SONumber AND class_id4 != 'LABOR'
	
	RETURN @Result

END
```

The new logic is that I have to look at the value of qryP21_ProductivitySLM.sales_cost and if it's GT 0 then use that calcuation in the original function but if it's 0 I want to multiply unit_price by .25 in the original calculation, which I thought would just be something like this:


```
	SELECT @Result = 
		CASE
		WHEN sales_cost > 0 
		THEN sum(((qty_shipped / unit_size) * unit_price * (slmPerc / 100)))
		ELSE sum(((qty_shipped / unit_size) * (unit_price * .25) * (slmPerc / 100))) 
	END FROM qryP21_ProductivitySLM WHERE order_no = @SONumber AND class_id4 != 'LABOR';
```

But sql yells at me and says: Column 'qryP21_ProductivitySLM.sales_cost' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
I don't believe I want to group by it or aggregate it so I am not sure how to accomplish the conditional logic.

----------


## MMock

Nevermind!  Not sure why I got hung up on it having to be conditional logic!


```
ALTER FUNCTION [dbo].[fn_ProfitAndLossCalculateTotalItemSell] 
(
	@SONumber nvarchar(8)
)
RETURNS decimal(9,2)
AS
BEGIN

	DECLARE @Result decimal(9,2)
declare @oneSum AS decimal(9,2)
declare @anotherSum AS decimal(9,2)

select @oneSum = SUM((qty_shipped / unit_size) * unit_price * (slmPerc / 100)) FROM qryP21_ProductivitySLM WHERE order_no = '1066645' AND class_id4 != 'LABOR' AND sales_cost > 0
select @anotherSum = SUM((qty_shipped / unit_size) * (unit_price * .25) * (slmPerc / 100)) FROM qryP21_ProductivitySLM WHERE order_no = '1066645' AND class_id4 != 'LABOR' AND sales_cost = 0
select @Result = @oneSum + @anotherSum
Return @Result
END
GO
```

----------


## wqweto

Note that *@SONumber* parameter is never used in your final function.

Btw, you cannot use * and / in SQL Server without heeding the intermediate data-types when you are using DECIMAL columns or you risk quickly losing precision by defaulting to DECIMAL(37, 6) intermediaries.

cheers,
</wqw>

----------


## MMock

Thank you for the tips and observations!  I had left '1066645' hardcoded in my snip, but that would be a @SONumber passed in which I did  remember to change before creating in the db!

----------

