Skip to content

SQL Server: Translate Math.Max/Min in non-aggregate context #27794

@yesmey

Description

@yesmey

Today Math.Max / Math.Min is not being translated for SQL Server - only for sqlite as introduced in #10533

Transact-SQL does not have an MIN or MAX function, so there's no 1-to-1 mapping, but it is however possible to translate it into a CASE WHEN statement.
For example

Math.Max(Column1, Column2)

is equivalent to

CASE
    WHEN Column1 >= Column2 THEN Column1
    ELSE Column2
END

As a suggestion, I made a reference implementation by adding the following translation to SqlServerMathTranslator.cs

For Math.Max it looks like this:

var left = arguments[0];
var right = arguments[1];

var typeMapping = ExpressionExtensions.InferTypeMapping(left, right);
left = _sqlExpressionFactory.ApplyTypeMapping(left, typeMapping);
right = _sqlExpressionFactory.ApplyTypeMapping(right, typeMapping);

return _sqlExpressionFactory.Case(
    new[] { new CaseWhenClause(_sqlExpressionFactory.GreaterThanOrEqual(left, right), left) },
    right);

and Math.Min:

// same type mapping...
return _sqlExpressionFactory.Case(
    new[] { new CaseWhenClause(_sqlExpressionFactory.LessThanOrEqual(left, right), left) },
    right);

Link to my branch of the example

Metadata

Metadata

Assignees

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions