Pergunta

Coalesce seems to work with any number of parameters and return the first one that is not null. How can I write a function like that? One that does not have a fixed number of parameters?

An example of the usage of a function fMax:

select Length = dbo.fMax(box.Height, box.Width, box.Depth)
from dbo.tBox box
where box.ShipmentId = 1234

With such a function I would not have to write something like this:

select Length = (
   select MAX(side)
   from (values (box.Height), (box.Width), (box.Depth)) as sides(side))
from dbo.tBox box
where box.ShipmentId = 1234
Foi útil?

Solução 2

Unfortunately, after trying that out, I am pretty sure that you cannot write COALESCE-like functions yourself in T-SQL.

I was pretty sure that you can use socalled CLR-Functions that you can code for example in C# to make up for some lacking features in SQL-Server. However I have to agree with the comment below, that this does not free you from the need to provide a parameter list in sql to introduce the new function in which you still would have that restriction.

So in short, you cannot code such functions yourself for T-SQL.

Outras dicas

If you use SQL Server 2008 and above you can use the Table-Valued Parameters.

As the other respondants say, I don't think you can do exactly what you ask for.

However I think you could make a reasonable approximation using default parameters. If you know a reasonable upper limit, the you could define a function something like this:

--Edit

Turns out you can't have default values on a UDF. Or rather you can define them, but you still have to specify the values when calling the function

That means the best you can do is to have function with the maximum number of parameters:

CREATE FUNCTION dbo.fMax
(
    @Value1 float,
    @Value2 float,
    @Value3 float,
    @Value4 float
)
RETURNS float
AS
BEGIN
  DECLARE @Result float

  SELECT @Value1 = COALESCE(@Value1, @Value2, @Value3, @Value4)
  SELECT @Value2 = COALESCE(@Value2, @Value1, @Value3, @Value4)
  SELECT @Value3 = COALESCE(@Value3, @Value1, @Value2, @Value4)
  SELECT @Value4 = COALESCE(@Value4, @Value1, @Value2, @Value3)

  SELECT @Result = @Value1

  IF (@Value2 > @Result)
    SELECT @Result = @Value2

  IF (@Value3 > @Result)
    SELECT @Result = @Value3

  IF (@Value4 > @Result)
    SELECT @Result = @Value4

  RETURN @Result
END

and call it like this:

SELECT dbo.fMax(1, 5, 4, null)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top