我正在使用DATEDIFF( day, date1, date2)
,效果很好。
如果数字是正数,是否有可能有加号,如果数字是负数,则有负数。
答案 0 :(得分:2)
您可以将输出转换或转换为字符串,然后根据需要添加“+”符号(如果是负数,则减号已经存在。
Case When DATEDIFF( day, date1, date2) > 0 Then '+' Else '' End + Cast (DATEDIFF( day, date1, date2) as VarChar(10))
这是一个例子
;With MyTable as
(
Select GETDATE() as Date1, GetDate()+10 as Date2
)
Select
Case When DATEDIFF( day, date1, date2) > 0 Then '+' Else '' End + Cast (DATEDIFF( day, date1, date2) as VarChar(10))
From MyTable
;With MyTable as
(
Select GETDATE() as Date1, GetDate()-10 as Date2
)
Select
Case When DATEDIFF( day, date1, date2) > 0 Then '+' Else '' End + Cast (DATEDIFF( day, date1, date2) as VarChar(10))
From MyTable
答案 1 :(得分:2)
您可以使用条件格式:
SELECT FORMAT(DATEDIFF( day, date1, date2),'+#;-#;0')
FROM MyTable
答案 2 :(得分:1)
您可以使用
DECLARE @date1 as datetime
DECLARE @date2 as datetime
DECLARE @datediff as varchar(10)
SET @date1 = GETDATE() - 10
SET @date2 = GETDATE() - 1
SET @datediff = DATEDIFF( day, @date1, @date2)
SELECT Case
When @datediff > 0 Then '+'
Else '-'
End + @datediff