简体   繁体   中英

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

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 :)

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.

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM