2015-01-14 44 views

回答

2

可以CAST或轉換輸出爲一個字符串,然後如果需要的話(負已經在那裏如果是負數添加「+」號。

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

您可以使用

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 
2

您可以使用條件格式:

SELECT FORMAT(DATEDIFF(day, date1, date2),'+#;-#;0') 
FROM MyTable