[英]Datetime comparison error in sql?
我已經使用日期和時間驗證來安排報告......我必須安排該報告僅用於未來的日期和時間而不是之前的日期和時間..我已經使用過這個
declare @Dt varchar(50)
declare @Hr varchar(50)
declare @trandate_time_tmp as TIME(0)
select @trandate_time_tmp = getdate()
set @Dt = DATEDIFF (D,@schedule_date ,@trandate_tmp )
set @Hr = DATEDIFF (S,@schedule_date ,@trandate_time_tmp )
if ( @Dt > 0)
begin
raiserror('Schedule Date should not be earlier than system date',16,1)
return
end
if ( @Hr > 0)
begin
raiserror('Schedule Time should not be earlier than system time',16,1)
return
end
對於日期部分,它正在檢查正確,但是對於時間,它會拋出錯誤
The datediff function resulted in an overflow. The number of dateparts separating two date/time instances is too large. Try to use datediff with a less precise datepart.
不完全回答你的問題,但也許解決你的問題。 您不需要使用DATEDIFF並檢查結果,您可以只比較兩個日期。
IF ( @schedule_date <= GETDATE() )
BEGIN
RAISERROR('Schedule date should not be earlier than system date', 16, 1)
RETURN
END
我在嘗試從日期創建Unix時間戳時遇到了同樣的問題,
這是我嘗試做的一個例子:
select DATEDIFF(second,'1970-01-01','2200-01-11');
它會溢出,因為DATEDIFF試圖返回一個有符號整數 - 它只能容納超過68年的秒數。
為了獲得Unix時間戳(我需要這樣我可以將其提供給Sphinx Search),您可以先在幾分鍾內獲得差異,然后將結果轉換為大整數,然后乘以60秒:
select CAST(DATEDIFF(minute,'1970-01-01','2200-01-11') AS BIGINT) * 60;
現在我們應該能夠處理差異長達4000年左右的日期。 如果您需要更多空間,只需更換更大更大間隔的分鍾,並相應地更改秒數乘數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.