开发者

Understanding SQL Server behaviour with min(datetime)

开发者 https://www.devze.com 2023-03-14 08:44 出处:网络
(long story short, was just a dumb assumption by me, I was sure a column was a datetime and it wasn\'t - so don\'t expect to find anything interesting in this question, leaving it here so that dems ge

(long story short, was just a dumb assumption by me, I was sure a column was a datetime and it wasn't - so don't expect to find anything interesting in this question, leaving it here so that dems gets his rightfully accepted answer)

I wrote a simple query like this:

SELECT ID, MIN(DateMadeActive) AS DateMadeActive
FROM RecordStateField WHERE RecordStatusID in (2, 3)
GROUP BY ID

Where DateMadeActive is a datetime column. This returned what I expected:

ID  DateMadeActive
1   20/06/2011 16:15:04
2   20/06/2011 16:14:28

Now I inserted this into a new table, but inserting the result of MIN(DateMadeActive) into a datetime column of another table gave me this error:

Msg 8115, Level 16, State 2, Line 1
Arithmetic overflow error converting expression to data type datetime.

So to test this I change my select to this:

SELECT ID, CAST(Min(DateMadeActive) as datetime) AS DateMadeActive
FROM RecordStateField WHERE RecordStatusID in (2, 3)
GROUP BY ID

Same exception. I can write it like this and make it work:

SELECT ID, CONVERT(datetime, Min(DateMadeActive), 103) AS DateMadeActive
FROM RecordStateField WHERE RecordStatusID in (2, 3)
GROUP BY ID

So I can get it working, but this confuses me. The documentation for MIN(expression) says the return type should be the same as expression, but what seems to be happening is that MIN(datetime) is returning nvarchar(255). I can confirm t开发者_如何学运维his by running this:

SELECT ID, Min(DateMadeActive) AS DateMadeActive
INTO TestTable
FROM RecordStateField WHERE RecordStatusID in (2, 3)
GROUP BY ID

And I can see that the DateMadeActive column is of type nvarchar(255). Anyone shed any light on this? Just a documentation bug in MSDN?


It looks to me that DateMadeActive in [RecordStateField] is a VARCHAR(255) field. Could you post the table definitions?

I ask this because MIN() has neve rchanged the type for me before. And so if the result is a VARCHAR(255) it seems the input must also be a VARCHAR(255)

0

精彩评论

暂无评论...
验证码 换一张
取 消