Date without the time - sql

I'm working with SQL Server 2005.
I have a column called purchase_time of type datetime. How do I select this column with the time part - just the date.
Thanks,
Barry
EDIT:
Would it be safe to get the datetime and split it via Python on the first space, or is this format locale dependant?

In versions < 2008 (which, based on other comments to some of the answers, I believe you are running), the most efficient way is to keep it as a datetime type and use date math to avoid string conversions.
SELECT DATEADD(DAY, DATEDIFF(DAY, '20000101', purchase_time), '20000101')
FROM dbo.table;
EDIT
If you want the date only for display purposes, not for calculations or grouping, that is probably best handled at the client. You can do it in SQL simply by saying:
SELECT dt = CONVERT(CHAR(10), purchase_time, 120)
FROM dbo.table;

In SQL Server 2008 you can use the newly added date type:
select convert(date, purchase_time) from TableName
Update:
In versions prior to SQL 2008, I used the following solution for this problem:
select convert(datetime, convert(int, convert(float, purchase_time)))
from TableName

Related

Is there an equivalent to sysdate-1/24 in SQL server?

I've tried looking around for this but I can't find an answer that seems to work with the code I'm using. Basically, the below query searches on any result from the current date. I'm trying to make it so it will search only on the last hour.
In oracle I could do this using sysdate-1/24, is there a simple equivalent within SQL server? Bearing in mind I'm already using cast to get the current sysdate.
Select distinct m_record_server
from search_recording_file1
where tr_date_recorded >= cast(convert(varchar(10), getdate(), 110) as datetime)
and m_record_server is not null
You can use:
getdate() - 1.0/24
SQL Server allows you to use such arithmetic on datetime.
The more common way would be:
dateadd(hour, -1, getdate())
In your query, you do not need to cast to a string at all:
Select distinct m_record_server
from search_recording_file1
where tr_date_recorded >= getdate() - 1.0/24 and m_record_server is not null;
If you want the date that was there one hour ago (which seems to be the intent of the code, if not the rest of the question):
Select distinct m_record_server
from search_recording_file1
where tr_date_recorded >= cast(getdate() - 1.0/24 as date) and m_record_server is not null;

'DATE' is not a recognized built-in function name

I wish to find all records of the current day. I have a field Date of type DATE.
I am getting error on sql server
'DATE' is not a recognized built-in function name.
on this line
(DATE(EnterDate) = CURDATE() )
As the error states, there is no DATE function in SQL Server 2008 or 2012 (you tagged both so I'm not sure which you're targeting). You can, however, cast to a date type in SQL Server 2008 and above:
WHERE EnterDate = CONVERT(date,GETDATE())
Note that there's no CURDATE function either, so I've translated that to GETDATE()
Use the following condition in your where cluase
WHERE CAST(DateColumn AS DATE) = CAST(GETDATE() AS DATE)
^------------ Your Column Name with `Date` or 'DateTime' data type
CURDATE() is a mysql function, In Sql-Server we have GETDATE() function to get current date and time.
More efficient one is
WHERE EnterDate > DATEADD(dd, -1, DATEDIFF(dd, 0, GETDATE()))
Thanks #D Stanley #marc_S and #Mihai
Finally I get it done by
WHERE EnterDate > Convert(DATETIME,Convert(varchar,DATEADD(DAY,0,GETDATE()),101))
This is not the exact answer but example how to trim the time part from the date time variable
CONVERT(VARCHAR(10),date_manufactured,10) =CONVERT(VARCHAR(10),#startdate,10))

how to remove time from datetime

The field DATE in the database has the following format:
2012-11-12 00:00:00
I would like to remove the time from the date and return the date like this:
11/12/2012
First thing's first, if your dates are in varchar format change that, store dates as dates it will save you a lot of headaches and it is something that is best done sooner rather than later. The problem will only get worse.
Secondly, once you have a date DO NOT convert the date to a varchar! Keep it in date format and use formatting on the application side to get the required date format.
There are various methods to do this depending on your DBMS:
SQL-Server 2008 and later:
SELECT CAST(CURRENT_TIMESTAMP AS DATE)
SQL-Server 2005 and Earlier
SELECT DATEADD(DAY, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP), 0)
SQLite
SELECT DATE(NOW())
Oracle
SELECT TRUNC(CURRENT_TIMESTAMP)
Postgresql
SELECT CURRENT_TIMESTAMP::DATE
If you need to use culture specific formatting in your report you can either explicitly state the format of the receiving text box (e.g. dd/MM/yyyy), or you can set the language so that it shows the relevant date format for that language.
Either way this is much better handled outside of SQL as converting to varchar within SQL will impact any sorting you may do in your report.
If you cannot/will not change the datatype to DATETIME, then still convert it to a date within SQL (e.g. CONVERT(DATETIME, yourField)) before sending to report services and handle it as described above.
just use, (in TSQL)
SELECT convert(varchar, columnName, 101)
in MySQL
SELECT DATE_FORMAT(columnName, '%m/%d/%Y')
I found this method to be quite useful. However it will convert your date/time format to just date but never the less it does the job for what I need it for. (I just needed to display the date on a report, the time was irrelevant).
CAST(start_date AS DATE)
UPDATE
(Bear in mind I'm a trainee ;))
I figured an easier way to do this IF YOU'RE USING SSRS.
It's easier to actually change the textbox properties where the field is located in the report. Right click field>Number>Date and select the appropriate format!
SELECT DATE('2012-11-12 00:00:00');
returns
2012-11-12
Personally, I'd return the full, native datetime value and format this in the client code.
That way, you can use the user's locale setting to give the correct meaning to that user.
"11/12" is ambiguous. Is it:
12th November
11th December
For more info refer this: SQL Server Date Formats
[MM/DD/YYYY]
SELECT CONVERT(VARCHAR(10), cast(dt_col as date), 101) from tbl
[DD/MM/YYYY]
SELECT CONVERT(VARCHAR(10), cast(dt_col as date), 103) from tbl
Live Demo
TSQL
SELECT CONVERT(DATE, GETDATE()) // 2019-09-19
SELECT CAST(GETDATE() AS DATE) // 2019-09-19
SELECT CONVERT(VARCHAR, GETDATE(), 23) // 2019-09-19
In mysql at least, you can use DATE(theDate).
You may try the following:
SELECT CONVERT(VARCHAR(10),yourdate,101);
or this:
select cast(floor(cast(urdate as float)) as datetime);
Use this SQL:
SELECT DATE_FORMAT(date_column_here,'%d/%m/%Y') FROM table_name;

Oracle to SQL server Date conversion

I would like to convert an Oracle SQL query into SQL server query.
But I encountered a problem with the following line :
AND to_date(to_char(M_DATE,'DD-MM-YYYY')) = '27/01/12'
M_DATE : DATE NOT NULL
I use
to_char(DATE,'DD-MM-YYYY')
in order to get their data like that : DD-MM-YYYY 00:00:00.000 (data are stocked like : 25/02/12 15:32:06.578)
So I searched on the Internet, but I didn't find any available solution. But I'm not an experienced SQL user, so if anybody know the solution..
Thanks
In general when removing any time values from a date I would use Date functions rather than converting to string
DATEADD(DAY, 0, DATEDIFF(DAY, 0, GETDATE()))
instead of
CONVERT(VARCHAR, GETDATE(), 103)
Although the end result is the same you are maintaining date format and while I have no specific results sets to prove it conclusively I have found this to be much quicker when dealing with large quantities of data.
In Oracle, I would remove the time element of a datetime using trunc - like so:
AND trunc(M_DATE) = ...
In SQLServer, I would convert to a date - like so:
AND convert(date,M_DATE) = ...
SELECT CONVERT(VARCHAR(25), GETDATE(), 131)
You could just do:
AND convert(varchar(8), M_DATE, 3) = '27/01/12'
Of course, that won't work if you have dates from other centuries.
I'm not sure what you mean by "data are stocked like"; be aware that the Microsoft SQL Server DATE type only has a precision of one day. If you want to have the time as well as the day, you should use the DATETIME2 type

Best approach to remove time part of datetime in SQL Server

Which method provides the best performance when removing the time portion from a datetime field in SQL Server?
a) select DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)
or
b) select cast(convert(char(11), getdate(), 113) as datetime)
The second method does send a few more bytes either way but that might not be as important as the speed of the conversion.
Both also appear to be very fast, but there might be a difference in speed when dealing with hundreds-of-thousands or more rows?
Also, is it possible that there are even better methods to get rid of the time portion of a datetime in SQL?
Strictly, method a is the least resource intensive:
a) select DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)
Proven less CPU intensive for the same total duration a million rows by someone with way too much time on their hands: Most efficient way in SQL Server to get a date from date+time?
I saw a similar test elsewhere with similar results too.
I prefer the DATEADD/DATEDIFF because:
varchar is subject to language/dateformat issues
Example: Why is my CASE expression non-deterministic?
float relies on internal storage
it extends to work out first day of month, tomorrow, etc by changing "0" base
Edit, Oct 2011
For SQL Server 2008+, you can CAST to date i.e. CAST(getdate() AS date). Or just use date datatype so no time to remove.
Edit, Jan 2012
A worked example of how flexible this is: Need to calculate by rounded time or date figure in sql server
Edit, May 2012
Do not use this in WHERE clauses and the like without thinking: adding a function or CAST to a column invalidates index usage. See number 2 here Common SQL Programming Mistakes
Now, this does have an example of later SQL Server optimiser versions managing CAST to date correctly, but generally it will be a bad idea ...
Edit, Sep 2018, for datetime2
DECLARE #datetime2value datetime2 = '02180912 11:45' --this is deliberately within datetime2, year 0218
DECLARE #datetime2epoch datetime2 = '19000101'
select DATEADD(dd, DATEDIFF(dd, #datetime2epoch, #datetime2value), #datetime2epoch)
In SQL Server 2008, you can use:
CONVERT(DATE, getdate(), 101)
Of-course this is an old thread but to make it complete.
From SQL 2008 you can use DATE datatype so you can simply do:
SELECT CONVERT(DATE,GETDATE())
In SQL Server 2008, there is a DATE datetype (also a TIME datatype).
CAST(GetDate() as DATE)
or
declare #Dt as DATE = GetDate()
SELECT CAST(FLOOR(CAST(getdate() AS FLOAT)) AS DATETIME)
...is not a good solution, per the comments below.
I would delete this answer, but I'll leave it here as a counter-example since I think the commenters' explanation of why it's not a good idea is still useful.
Here's yet another answer, from another duplicate question:
SELECT CAST(CAST(getutcdate() - 0.50000004 AS int) AS datetime)
This magic number method performs slightly faster than the DATEADD method. (It looks like ~10%)
The CPU Time on several rounds of a million records:
DATEADD MAGIC FLOAT
500 453
453 360
375 375
406 360
But note that these numbers are possibly irrelevant because they are already VERY fast. Unless I had record sets of 100,000 or more, I couldn't even get the CPU Time to read above zero.
Considering the fact that DateAdd is meant for this purpose and is more robust, I'd say use DateAdd.
SELECT CAST(CAST(GETDATE() AS DATE) AS DATETIME)
I really like:
[date] = CONVERT(VARCHAR(10), GETDATE(), 120)
The 120 format code will coerce the date into the ISO 8601 standard:
'YYYY-MM-DD' or '2017-01-09'
Super easy to use in dplyr (R) and pandas (Python)!
BEWARE!
Method a) and b) does NOT always have the same output!
select DATEADD(dd, DATEDIFF(dd, 0, '2013-12-31 23:59:59.999'), 0)
Output: 2014-01-01 00:00:00.000
select cast(convert(char(11), '2013-12-31 23:59:59.999', 113) as datetime)
Output: 2013-12-31 00:00:00.000
(Tested on MS SQL Server 2005 and 2008 R2)
EDIT: According to Adam's comment, this cannot happen if you read the date value from the table, but it can happen if you provide your date value as a literal (example: as a parameter of a stored procedure called via ADO.NET).
See this question:
How can I truncate a datetime in SQL Server?
Whatever you do, don't use the string method. That's about the worst way you could do it.
Already answered but ill throw this out there too...
this suposedly also preforms well but it works by throwing away the decimal (which stores time) from the float and returning only whole part (which is date)
CAST(
FLOOR( CAST( GETDATE() AS FLOAT ) )
AS DATETIME
)
second time I found this solution... i grabbed this code off
CAST(round(cast(getdate()as real),0,1) AS datetime)
This method does not use string function. Date is basically a real datatype with digits before decimal are fraction of a day.
this I guess will be faster than a lot.
For me the code below is always a winner:
SELECT CONVERT(DATETIME, FLOOR(CONVERT(FLOAT,GETDATE())));
select CONVERT(char(10), GetDate(),126)
Strip time on inserts/updates in the first place. As for on-the-fly conversion, nothing can beat a user-defined function maintanability-wise:
select date_only(dd)
The implementation of date_only can be anything you like - now it's abstracted away and calling code is much much cleaner.
I think you mean
cast(floor(cast(getdate()as float))as datetime)
real is only 32-bits, and could lose some information
This is fastest
cast(cast(getdate()+x-0.5 as int)as datetime)
...though only about 10% faster(about 0.49 microseconds CPU vs. 0.58)
This was recommended, and takes the same time in my test just now:
DATEADD(dd, DATEDIFF(dd, 0, getdate()), 0)
In SQL 2008, the SQL CLR function is about 5 times faster than using a SQL function would be, at 1.35 microseconds versus 6.5 microsections, indicating much lower function-call overhead for a SQL CLR function versus a simple SQL UDF.
In SQL 2005, the SQL CLR function is 16 times faster, per my testing, versus this slow function:
create function dateonly ( #dt datetime )
returns datetime
as
begin
return cast(floor(cast(#dt as float))as int)
end
How about select cast(cast my_datetime_field as date) as datetime)? This results in the same date, with the time set to 00:00, but avoids any conversion to text and also avoids any explicit numeric rounding.
I think that if you stick strictly with TSQL that this is the fastest way to truncate the time:
select convert(datetime,convert(int,convert(float,[Modified])))
I found this truncation method to be about 5% faster than the DateAdd method. And this can be easily modified to round to the nearest day like this:
select convert(datetime,ROUND(convert(float,[Modified]),0))
Here I made a function to remove some parts of a datetime for SQL Server. Usage:
First param is the datetime to be stripped off.
Second param is a char:
s: rounds to seconds; removes milliseconds
m: rounds to minutes; removes seconds and milliseconds
h: rounds to hours; removes minutes, seconds and milliseconds.
d: rounds to days; removes hours, minutes, seconds and milliseconds.
Returns the new datetime
create function dbo.uf_RoundDateTime(#dt as datetime, #part as char)
returns datetime
as
begin
if CHARINDEX( #part, 'smhd',0) = 0 return #dt;
return cast(
Case #part
when 's' then convert(varchar(19), #dt, 126)
when 'm' then convert(varchar(17), #dt, 126) + '00'
when 'h' then convert(varchar(14), #dt, 126) + '00:00'
when 'd' then convert(varchar(14), #dt, 112)
end as datetime )
end
Just in case anyone is looking in here for a Sybase version since several of the versions above didn't work
CAST(CONVERT(DATE,GETDATE(),103) AS DATETIME)
Tested in I SQL v11 running on Adaptive Server 15.7
If possible, for special things like this, I like to use CLR functions.
In this case:
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlDateTime DateOnly(SqlDateTime input)
{
if (!input.IsNull)
{
SqlDateTime dt = new SqlDateTime(input.Value.Year, input.Value.Month, input.Value.Day, 0, 0, 0);
return dt;
}
else
return SqlDateTime.Null;
}
I, personally, almost always use User Defined functions for this if dealing with SQL Server 2005 (or lower version), however, it should be noted that there are specific drawbacks to using UDF's, especially if applying them to WHERE clauses (see below and the comments on this answer for further details). If using SQL Server 2008 (or higher) - see below.
In fact, for most databases that I create, I add these UDF's in right near the start since I know there's a 99% chance I'm going to need them sooner or later.
I create one for "date only" & "time only" (although the "date only" one is by far the most used of the two).
Here's some links to a variety of date-related UDF's:
Essential SQL Server Date, Time and DateTime Functions
Get Date Only Function
That last link shows no less than 3 different ways to getting the date only part of a datetime field and mentions some pros and cons of each approach.
If using a UDF, it should be noted that you should try to avoid using the UDF as part of a WHERE clause in a query as this will greatly hinder performance of the query. The main reason for this is that using a UDF in a WHERE clause renders that clause as non-sargable, which means that SQL Server can no longer use an index with that clause in order to improve the speed of query execution. With reference to my own usage of UDF's, I'll frequently use the "raw" date column within the WHERE clause, but apply the UDF to the SELECTed column. In this way, the UDF is only applied to the filtered result-set and not every row of the table as part of the filter.
Of course, the absolute best approach for this is to use SQL Server 2008 (or higher) and separate out your dates and times, as the SQL Server database engine is then natively providing the individual date and time components, and can efficiently query these independently without the need for a UDF or other mechanism to extract either the date or time part from a composite datetime type.
I would use:
CAST
(
CAST(YEAR(DATEFIELD) as varchar(4)) + '/' CAST(MM(DATEFIELD) as varchar(2)) + '/' CAST(DD(DATEFIELD) as varchar(2)) as datetime
)
Thus effectively creating a new field from the date field you already have.