Storing the date Only in SQL Server 2005 - sql

How do I avoid storing the time portion of a datetime in SQL Server, i.e. if I have a value of 2011-01-01 00:00:00.000 I want to store only 2011-01-01?
I want to ensure that only the date portion is stored.

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.

SQL Server Date Formats.

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.

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 :)

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.

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))

Just represent the date as a yyyMMdd integer value.

Related

Time in datatime field

I have a field that stores the date and time but need to extract this so it only shows the time but shows the date as 01/01/1900.
I can extract the time using the below but need to include the data of 01/01/1900
convert(varchar(12), w.created, 114)
If you are using SQL Server, then you can do:
select cast('1900-01-01' as datetime) + cast(cast(w.created as time) as datetime)
This returns the value as a datetime.
SQL Server has a time data type. It is unclear why you would want to add in a fake date, but you can.

How to cast the DateTime to Time

I am casting DateTime field to Time by using CAST Syntax.
select CAST([time] as time) as [CSTTime]
DateTime
2015-03-19 00:00:00.000
Present Output : Time
03:05:36.0000000
I need only HH:MM:SS and not Milliseconds or 0000's
How to filter or Cast it to exact HH:MM:SS Format.
Time is not stored with its display format in SQL Server.
Therefore, from the user perspective, you can say that it has no format.
Of course, that's not completely accurate since it does have a storage format, but as an average user you can't really use it.
This is true for all date and time data types:
Date, DateTimeOffset, DateTime2, SmallDateTime, DateTime and Time.
If you need a format then you don't need to cast to time but to a char. Use Convert to get the char you need:
SELECT CONVERT(char(10), [time], 108) as CSTTime
Here is some background data if you're interested:
In this article published in 2000 the writer explains in depth how SQL Server treats dates and times. I doubt if anything significant changed between 2000 and 2015 in the way SQL Server stores date, time and datetime values internally.
Here are the relevant quotes, if you don't want to read all of it:
So how does SQL Server internally store the dates? It uses 8 bytes to store a datetime value—the first 4 for the date and the second 4 for the time. SQL Server can interpret both sets of 4 bytes as integers.
........
........
SQL Server stores the second integer for the time as the number of clock ticks after midnight. A second contains 300 ticks, so a tick equals 3.3 milliseconds (ms).
since time is actually stored as a 4 byte integer, it really doesn't have a format as an integral part of the data type.
You might also want to check out this article for a more detailed explanation with code samples.
You can achieve it with CAST just simple use TIME(0) datatype in following:
SELECT CAST('2015-03-19 01:05:06.289' AS TIME(0))
OUTPUT:
01:05:06
SQL Server 2008:
select cast(MyDate as time) [time] from yourtable
Earlier versions:
select convert(char(5), MyDate , 108) [time] from yourtable
Other Options:
SELECT CONVERT(VARCHAR(20), GETDATE(), 114)
The simplest way to get the time from datetime without millisecond stack is:
SELECT CONVERT(time(0),GETDATE())
Hour and Minute
SELECT substring(CONVERT(VARCHAR, GETDATE(), 108),0,6) AS Time

I want to convert a whole column into the date format of yyyymmdd, I do not want the current date

I want to convert a whole column into the date format of yyyymmdd, I do not want the current date, thus I cannot use getdate() command, there is already data in the column, I just need the right command to convert the whole column into yyyymmdd format.
The column I am using is FIELD_034 and the table is Sur_CompassAuto1_1_7_fetch.
I am using SQL Server.
Thank you
I fully agree with the paqogomez's response, but instead of date style of 111, better use 112.
The output for the statement
SELECT CONVERT(VARCHAR(10), FIELD_034, 111)
will result in yyyy/MM/dd. Where as,
SELECT CONVERT(VARCHAR(10), FIELD_034, 112)
will return yyyyMMdd, which is what he needed.
A common misconception is that a datetime has a format. If you are storing your dates as a datetime, then you can output it in any format.
It sounds as though you might be storing your values as a Varchar. You would be better off converting your varchar dates into a datetime, then you can do whatever you want with them
That said, if you HAVE FIELD_034 as a DateTime, then its as easy as
SELECT CONVERT(VARCHAR(10), FIELD_034, 112)
from Sur_CompassAuto1_1_7_fetch
If the field is a varchar its similar:
SELECT CONVERT(datetime, FIELD_034, 112)
from Sur_CompassAuto1_1_7_fetch
The difficulty of this one is if you have your values in different or nonstandard formats. Then it would require some clean up to make the query work.
Edit: as #AArnold says, its 112 instead of 111. Date formats are subtle.

SQL - comparing date parameter to datetime

In a SQL Server table, I have a field named Timestamp, which is a 'datetime' field. On a screen I have created, a user will pass in a date (no time), and I need to return all the records for that date.
Just doing Timestamp = #Date doesn't seem to work unless the time in the field is 00:00:00. What is the most efficient way of doing this?
Since you're on SQL Server 2008, you can use the DATE datatype.
Do a comparison between
CAST(Timestamp AS DATE) = #Date
That should work and look just at the date - no time portion.
In general you should think about the data from a specific date as data that falls in a range, not at a single point in time. So ideally your query should use a range, such as:
WHERE [Timestamp] >= #Date
AND [Timestamp] < DATEADD(DAY, 1, #Date)
In this case, luckily, the optimizer is smart and will still use an index if you use CONVERT(DATE, [timestamp]) against the column. However in a lot of cases you need to be careful because this will often make your clause non-sargable.
PS Timestamp is a horrible column name. It's a data type in SQL Server which has nothing to do with date or time.
A common technique for truncating the time part off a datetime value is to use the DATEDIFF and DATEADD functions. In your example it would be used like this to truncate the time part of the Timestamp field.
WHERE #DateEntered = DATEADD(DAY,0, DATEDIFF(DAY, 0, Timestamp))
Bascially it's taking the datetime value and finding the name of days since "the date represented by 0" (for lack of a better description) and then adding that number of days back. This effectively truncates time part.

how to convert datetime value to another date only format?

my datetime field looks like this:
2011-02-07 06:51:32.000 (yyyy-mm-dd)
User input is in this format:
02-07-2011 (only the date)
This should be converted to:
02-07-2011 00:00:00.000
i tried CONVERT:
CONVERT(VARCHAR(10),myDateTimeField,113)
but this only works with date values not with datetime.
please help!
I used the following function:
CONVERT(datetime,Cast(myDateInput AS Char (10)), 105)
thanks for all your answers! and my apoligizes for changing my question!
select convert(varchar, myDateTimeField, 105) ...
Source: http://www.mssqltips.com/sqlservertip/1145/date-and-time-conversions-using-sql-server/ and http://msdn.microsoft.com/en-us/library/aa226054(v=sql.80).aspx
Crystal has a function called Date; it takes either YYYY, MM, DD or a datetime as arguments and returns a date.
So I would suggest you make a formula to change the date to a datetime and display it.
date( mytable.mydatetimevar )
You should then be able to format this date as you want with the normal date field formatting options.
An alternative method of doing it is using Crystal's DatePart function to pull out the month, year, day and then restructure as required.
Try this:
select DATEPART(mm, myDateTimeField) + '-' +
DATEPART(dd, myDateTimeField) + '-' +
DATEPART(year, myDateTimeField)
I don't think it's surprising that a DATETIME field carries time information ;)
In fact, you shouldn't alter the field itself, as you would lose the database engine's ability to use date/time related functions with this field.
(the format used is ISO 8601 which helps the engine to easily identify the single parts)
As others said, it's good practice to format the date when you are retrieving it, either in your SELECT statement or in your application. (for more tips regarding this we would indeed need the information what sql server and what appliccation language you are using).
try converting with Style ID - 110
CONVERT(VARCHAR(10),myDateTimeField,110)
Result will be: 02-07-2011