What is the use of the hyphen before a function in SQL (SQLServer)

453 views Asked by At

I would like to find out what the logic behind the SQL Syntax is when including a hyphen before calling a SQL function enclosed in parentheses.

Here is the SQL:

IF (@StartDate > @EndDate)
BEGIN
    SET @EndDate = @StartDate
    SET @StartDate = @EndDate
END

DECLARE @nonworkingweekdays int

--now deal with public holidays
SELECT @nonworkingweekdays = count("Date") from 
(
    select distinct
    (
    CASE datepart(weekday,date)
            WHEN 1 THEN null --ignore sundays   
            WHEN 7 THEN null --ignore saturdays
            else "Date"
    END
    ) AS "date" 
    from publicholidays
) nonworkingweekdays 
WHERE 
"Date" is not null and 
"Date" between @StartDate and DATEADD(day, -1, @EndDate)

RETURN
    CASE WHEN @StartDate <= @EndDate
    THEN
        dbo.FullWeekDays(@StartDate, @EndDate) - @nonworkingweekdays
    ELSE
        -(dbo.FullWeekDays(@StartDate, @EndDate) - @nonworkingweekdays)
    END 

The logic I am confused about is in the else statement with the return statement at the bottom of this script.

Thanks in advance :)

3

There are 3 answers

0
David Browne - Microsoft On BEST ANSWER

It's the TSQL Unary Negative Operator:

Returns the negative of the value of a numeric expression (a unary operator). Unary operators perform an operation on only one expression of any one of the data types of the numeric data type category.

0
Sebastian Ho Chi Min On

The hyphen is there to reverse the sign of the expression's value, because in the case you have there:

CASE WHEN @StartDate <= @EndDate
THEN
    dbo.FullWeekDays(@StartDate, @EndDate) - @nonworkingweekdays
ELSE
    -(dbo.FullWeekDays(@StartDate, @EndDate) - @nonworkingweekdays)
END 

you are returning the difference between the dates minus the nonworkingdays variable.

it is logically the best option, because you cant have a -1 days difference, you always need a positive integerin the difference.

be sure to make a way to differentiate between the types of return (when the startdate is greater than enddate and vice-versa)

1
Gordon Linoff On

It is a unary negation operator, so the same as (0 - <expression>).

That said, I am guessing that this is more simply expressed as:

RETURN ABS(dbo.FullWeekDays(@StartDate, @EndDate) - @nonworkingweekdays)