views:

155

answers:

7

How to avoid the time portion of the datetime in sql server. I wants only the date portion to insert my database. Thanks in Advance

+3  A: 

SQL Server Date Formats.

Swingley
+4  A: 

The DateTime data type ALWAYS stores the date AND time. So you are left with using CONVERT/CAST to obtain a particular format, or use the YEAR(), MONTH() or DAY() methods to isolate date details depending on your need.

OMG Ponies
Or you can just ignore the time portion of the column and let it default. Just make sure to feed it only dates when you are inserting/updating values.
Jeff Siver
+2  A: 

The easiest solution is just to not expose the time portion to the user. However, if you really need to make sure only the date part is stored, you could force the time portion to midnight/midday/any constant time before storing the value.

Tullo
+1  A: 

The built-in DATETIME data type stores both the date and time data. If you specify only the date portion then the time will be 12:00:00 or something like that.

Funny story: I saw a database once where there was a date and a time field, both stored the date and the time, but each was used only for half of the data. Some people do silly things :)

Nippysaurus
+1  A: 

If you cast a DateTime to an Int and back you will get a DateTime with 00:00 as the time part. So you could save all your dates as integers in the database.

idstam
If you cast a `DateTime` to an `INTEGER`, it will round the `DateTime` to the closest midnight. You need to cast to `FLOAT` first then to `INTEGER`.
Quassnoi
You are so right. I must have tried this (and ran all my unit tests) before noon.
idstam
+1  A: 

Either add a computed column:

dateonly AS CONVERT(DATETIME, CONVERT(CHAR(8), date_with_time, 112), 112)

or truncate your date right on insert:

INSERT
INTO     mytable (dateonly)
VALUES   CONVERT(DATETIME, CONVERT(CHAR(8), GETDATE(), 112), 112)

, making a CHECK on your dateonly column to raise an error when someone tries to insert a non-truncated value:

CHECK (dateonly = CONVERT(DATETIME, CONVERT(CHAR(8), date_with_time, 112), 112))
Quassnoi
A: 

Just represent the date as a yyyMMdd integer value.

pjp