1

我有我想插入到表中的数据。样本数据MM/DD/YYYY+ 1 天和12:00:00 PM

基本上我需要的是插入当前日期 + 1 天和 12:00:00 PM 的特定时间。

我的代码是这样的:

DECLARE @MyEstimatedDate as varchar(100)    ---TEMPORARY CONTAINER
DECLARE @MyEstimatedDate1 as varchar(100)   ---TEMPORARY CONTAINER
DECLARE @MyEstimatedDate2 as varchar(100)   ---TEMPORARY CONTAINER
DECLARE @MyEstimatedDate3 as DATETIME       ---FINAL DATA NEEDED. This is the data I want inserted.

SET @MyEstimatedDate = DATEADD(day,1,GETDATE()) 
SET @MyEstimatedDate1 = CONVERT(VARCHAR(100),@MyEstimatedDate,101)
SET @MyEstimatedDate2 = @MyEstimatedDate1 + ' 12:00:00 PM'
SET @MyEstimatedDate3 = cast(@MyEstimatedDate2 as datetime)  ---I believe this is the error

我得到的错误信息:

将 char 数据类型转换为 datetime 数据类型会导致 datetime 值超出范围。

4

3 回答 3

2

varchar只是在操作datetime数据时不要使用。SQL Server 2005 为您提供了足够的工具来避免转换。

The following is a more or less known method of dropping the time part from a datetime value:

SELECT DATEADD(DAY, DATEDIFF(DAY, 0, @InputDateTime), 0);

In the above example, DATEDIFF calculates the number of days between a date specified as 0 and the given date. The number of days is then added by the DATEADD function to the 0 date. The final result is a datetime value with the time of 00:00:00 and the same date as @InputDateTime. This is because the 0 date is an integer representation of 1900-01-01 00:00:00: its time part is zero and, since we have incremented it by a whole number of days, so is the result's time part.

Now, if instead of the DATEDIFF days you add DATEDIFF+1, you will get the next day. Furthermore, if instead of 0 as the date to be incremented you use 12:00, you will get the next day's noon, which appears to be what you want. So, the final expression will look like this:

SELECT DATEADD(DAY, DATEDIFF(DAY, 0, @InputDateTime) + 1, '12:00');

Since your input timestamp is supposed to be the current date & time, just replace @InputDateTime with GETDATE():

SELECT DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()) + 1, '12:00');
于 2013-02-10T20:53:37.607 回答
0

为什么不简单地做

cast(dateadd(day, 1, getdate()) as date)

那是午夜。中午做这个

dateadd(hour, 12, cast(cast(dateadd(day, 1, getdate()) as date) as datetime))  

忘记上面的,是错误的。

正确答案是

dateadd(hour, 12, cast(cast(dateadd(day, 1, getdate()) as date) as datetime))  

这次我什至测试了它。

于 2013-02-10T15:48:22.630 回答
0

datetime 类型包含日期+时间。在您的情况下,@MyEstimatedDate1 只需要一个日期

DECLARE @MyEstimatedDate varchar(100)    ---TEMPORARY CONTAINER
DECLARE @MyEstimatedDate1 varchar(100)   ---TEMPORARY CONTAINER
DECLARE @MyEstimatedDate2 varchar(100)   ---TEMPORARY CONTAINER
DECLARE @MyEstimatedDate3 DATETIME       ---FINAL DATA NEEDED. This is the data I want inserted.

SET @MyEstimatedDate = DATEADD(day, 1, GETDATE()) 
SET @MyEstimatedDate1 = CONVERT(VARCHAR(100), CAST(@MyEstimatedDate AS date), 101)
SET @MyEstimatedDate2 = @MyEstimatedDate1 + ' 12:00:00 PM'
SET @MyEstimatedDate3 = cast(@MyEstimatedDate2 as datetime)   ---I believ

或者简单易用

SELECT DATEADD(hour, 36, GETDATE() - CAST(GETDATE() AS time))
于 2013-02-10T15:53:25.513 回答