Avatar of Natchiket
Natchiket
Flag for United Kingdom of Great Britain and Northern Ireland asked on

Scalar function not behaving consistently in query

In the following scalar function,

a fractional value between 0.1 and 0.4 is set to 0.5

a fractional value of 0.6 and above is rounded up to the next integer

ALTER FUNCTION [dbo].[BHERound]
(
    @val float ) RETURNS float AS BEGIN     -- Declare the return variable here     declare @frac float      --fractional part of the value     declare @newfrac float     Set @frac = @val - round(@val,0,1)     set @newfrac = 0     If  @frac >= 0.1 and @frac <=0.4         set @newfrac = 0.5     else if @frac >= 0.6         set @newfrac = 1     else if @frac > 0.4 and @frac < 0.6         set @newfrac = 0.5     return     round(@val,0,1) + @newfrac END

Open in new window

this works fine in SMSS e.g.

select dbo.BHERound(1.6) , gives the answer 2, as expected


however the following query

select *,dbo.BHERound(RawBHE) as BHE from tblTESTRawBHE where PosRef='FCILLC002220'

Open in new window

returns

i.e 1.5 which is wrong, RawBHE is a FLOAT data type.

Microsoft SQL Server

Avatar of undefined
Last Comment
Pavel Celba

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Natchiket

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Pavel Celba

Why didn't you just use CEILING ?
DECLARE @n float = 1.6
SELECT CEILING((@n-0.099999999)*2)/2.0

Open in new window

Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes