2

In my database table fields are saved as 2013-02-15 00:00:00.000. I want they should be 2013-02-15 23:59:59.999. So how to convert 2013-02-15 00:00:00.000 to 02-15 23:59:59.999. In other words only change minimum to maximum time.

Imran Qadir Baksh - Baloch
  • 32,612
  • 68
  • 179
  • 322

3 Answers3

4
DECLARE @Time TIME = '23:59:59.999'
SELECT dateColumn + @Time
FROM tableName

SQL Fiddle Demo

Edit

Cast @time to datetime before (+)

DECLARE @Time TIME = '23:59:59.999'
SELECT dateColumn + CAST(@Time as DATETIME)
FROM tableName
Mudassir Hasan
  • 28,083
  • 20
  • 99
  • 133
2

Easily done:

SELECT dateCol + '23:59:59'
T McKeown
  • 12,971
  • 1
  • 25
  • 32
2

The datetime datatype is not accurate to thousandths of seconds, but rather only to 333rds of a second (details in BOL, it has to do with how the data is actually stored).

Run this for an example:

DECLARE @Test datetime = 'Feb 15, 2013'

PRINT convert(varchar(50), @Test, 109)

SET @Test = dateadd(ms, -1, @Test)
PRINT convert(varchar(50), @Test, 109)

SET @Test = dateadd(ms, -1, @Test)
PRINT convert(varchar(50), @Test, 109)

SET @Test = dateadd(ms, -1, @Test)
PRINT convert(varchar(50), @Test, 109)

PRINT ''

SET @Test = dateadd(ms, -3, @Test)
PRINT convert(varchar(50), @Test, 109)

SET @Test = dateadd(ms, -3, @Test)
PRINT convert(varchar(50), @Test, 109)

SET @Test = dateadd(ms, -3, @Test)
PRINT convert(varchar(50), @Test, 109)

This generates:

Feb 15 2013 12:00:00:000AM
Feb 15 2013 12:00:00:000AM
Feb 15 2013 12:00:00:000AM
Feb 15 2013 12:00:00:000AM

Feb 14 2013 11:59:59:997PM
Feb 14 2013 11:59:59:993PM
Feb 14 2013 11:59:59:990PM

So, the simplest way to update a datetime to the highest/last possible moment prior to, say, Feb 15, 2013, you need to subtract 3 milliseconds, as shown above. In a table, it would be something like:

UPDATE MyTable
 set MyDateTime = dateadd(ms, -3, MyDateTime)
Philip Kelley
  • 39,426
  • 11
  • 57
  • 92