Groups | Blog | Home
all groups > sql server (alternate) > july 2006 >

sql server (alternate) : select minimum between two values


Generale Cluster
7/27/2006 12:00:00 AM
Hello,
I need to select the minimum between the result of a function and a
number, but i can't find a smart way. By now I'm doing like the
following, but I think is very expensive because it evaluates the
function twice:

select case when (myfunction())<100 then (myfunction()) else 100 end

Any idea is appreciated.
Thank you
Regards


--
Bobbo
7/27/2006 8:21:31 AM
[quoted text, click to view]

Another, equally not-necessarily-smartest way, is to write your own
function. In fact, I wrote one today to work out the greater of two
numbers:

CREATE FUNCTION [dbo].[fnMathMax] (@a int, @b int)
RETURNS int AS
BEGIN

DECLARE @ret int
SET @ret = @a
IF @b > @a SET @ret = @b

RETURN @ret

END
Chris Cheney
7/27/2006 12:35:52 PM
Generale Cluster <alexcarraro@carrarosoftmasters.net> wrote in news:eaa556
$2nm$1@newsreader.mailgate.org:

[quoted text, click to view]

One way, but not necessarily the smartest way:

select min(a) from (select myfunction() a union select 100 a) t
Roy Harvey
7/27/2006 9:07:16 PM
Just a thought, but have you considered changing myfunction (or
writing a new version of myfunction) so that the limit is already
applied to the result it returns?

Roy

On Thu, 27 Jul 2006 12:39:34 +0200, Generale Cluster
[quoted text, click to view]
Hugo Kornelis
7/27/2006 10:05:06 PM
[quoted text, click to view]

Hi Generale,

And yet another not-necessarily-smartest way is the use of a derived
table. Like this:

SELECT CASE WHEN res < 100 THEN rest ELSE 100 END AS Result
FROM (SELECT dbo.MyFunction() AS res
FROM ...
WHERE ... ) AS der;

For this specific case, I think I like Chris' suggestion best. However,
there are other cases where you have multiple references to the result
of a calculation; in cases where you can't adapt Chris' suggestion, yoou
can always use the derived table technique.

--
AddThis Social Bookmark Button