How to cast datetime into date in SQL Server 2005 [duplicate] - sql-server

This question already has answers here:
How to return only the Date from a SQL Server DateTime datatype
(46 answers)
Closed 7 years ago.
I have used something like this:
select* from table where cast(CreatedDate as date) = cast(GETDATE() as DATE)
in SQL Server 2008R2 and it works perfectly. But when goes to 2005, it doesn't work because Date is not a defined system type. Can anyone let me know a way that works both 2005 and 2008R2?
The CreatedDate is default as current_timestamp and I want to get data with today's data only.

You can try this:
convert(DateTime, floor(convert(float, getdate())))
That gets rid of the time part, by converting it into the underlying float number and rounding down to the nearest integer. The integer part represents the date and the decimal part is the time, so converting the integer back to a DateTime give the same date you started with but without any time part.
You can also wrap it up as a scalar-valued function:
CREATE FUNCTION [dbo].[DateTrunc] (#date DateTime)
RETURNS DateTime
AS
BEGIN
return convert(DateTime, floor(convert(float, #date)))
END

Related

Is there any way to formate dates as MMDDYYYY instead of YYYYMMDD in SQL Server? [duplicate]

This question already has answers here:
SQL Server date format function
(3 answers)
How to get a date in YYYY-MM-DD format from a TSQL datetime field?
(25 answers)
Closed 3 years ago.
I've just been setting my dates as VARCHARs instead of dates because they need to maintain a MMDDYYYY format and I was wondering it there was a better way to be doing this. The standard date seems to just do it as YYYYMMDD
Store dates as dates (or datetime) in the database. You should be formatting dates in the presentation layer (on-screen, reports, etc.). That is the point where you use your tools' formatting capabilities to display dates in the desired format. Remember, the dates in most DBMS are stored as long integers. You're query tools are actually formatting those values into a formatted date that is displayed.
Here is a quick query to display today as a numeric:
SELECT 'Yesterday', CAST(DATEADD(DAY, -1, #Today) AS DECIMAL(32,20))
UNION
SELECT 'Today', CAST(#Today AS DECIMAL(32,20))
UNION
SELECT 'Tomorrow', CAST(DATEADD(DAY, 1, #Today) AS DECIMAL(32,20))
Output is as follows (the fraction should represent the time element, if I'm correct):
Today 43717.61447052469200000000
Tomorrow 43718.61447052469200000000
Yesterday 43716.61447052469200000000
Here is a query-level method of converting the presentation of GETDATE() in SQL Server:
SELECT CONVERT(VARCHAR, GETDATE(), 110)
Output:
09-11-2019

How can I convert datetimeoffset to datetime in SQL Server 2008? [duplicate]

This question already has answers here:
How can I convert a Sql Server 2008 DateTimeOffset to a DateTime
(6 answers)
Closed 7 years ago.
I just need to change the date format from datatimeoffset to datetime while pulling the data
I will quote to "RichardTheKiwi"
declare #createdon datetimeoffset
set #createdon = '2008-12-19 17:30:09.1234567 +11:00'
select CONVERT(datetime2, #createdon, 1)
--Output: 2008-12-19 06:30:09.12
select convert(datetimeoffset,CONVERT(datetime2, #createdon, 1))
--Output: 2008-12-19 06:30:09.1234567 +00:00
Converting using almost any style will cause the datetime2 value to be converted to UTC.
Also, conversion from datetime2 to datetimeoffset simply sets the offset at +00:00, per the below, so it is a quick way to convert from Datetimeoffset(offset!=0) to Datetimeoffset(+00:00)
For more information you can visit: How can I convert a Sql Server 2008 DateTimeOffset to a DateTime

Excel incorrectly converts Date into Int

I'm pulling the data from SQL database. I have a couple columns with date which need to be converted into Int type, but when I do this the date changes (-2 days). I tried Cast and Convert and it's always the same.
Converting to other type works fine and returns the correct date, but doesn't work for me. I need only the date part from datetime and it needs to be recognised as a date by Excel.
Why is this happening? Any ideas how to get it sorted?
I'm using the following query:
SELECT wotype3, CONVERT(INT,wo_date2 ,103), CAST(duedate AS int) FROM Tasks WHERE
duedate > DATEADD(DAY,1, GETDATE())
AND wo_date2>0
AND wo_date2<DATEADD(WEEK,3,GETDATE())
ORDER BY wotype3
I've had big problems with this, checking my SQL Server's calculation results with "expected results" which a user had created using Excel.
We had discrepancies just because of this 2-day date difference.
Why does it happen ?
Two reasons:
SQL Server uses a zero-based date count from Jan 1 1900, but Excel uses a 1-based date count from Jan 1 1900.
Excel has a bug in it (gasp!) which makes it think that the year 1900 was a leap year. It wasn't. SQL Server correctly refuses to let you have a date value containing "29-Feb-1900".
Combine these two discrepancies, and this is why all dates, from March 1 1900 onwards, are always 2-days out.
Apparently, this Excel bug is a known issue, to keep it in line with Lotus 1-2-3.
The Intentional Date Bug
Microsoft's own explanation
From now on, I think I'll justify bugs in my code with the same excuse.
;-)
For SQL Server 2008 and above, you can use the DATE datatype.
declare #dt datetime = '12/24/2013 10:45 PM' -- some date for example
SELECT #dt as OriginalDateTime, CAST(#dt as DATE) as OnlyDate
For versions prior to SQL Server 2008, you would need to truncate the time part using one or the other functions. Here is one way to do that:
declare #dt datetime = '12/24/2013 10:45 PM' -- some date for example
SELECT #dt as OriginalDateTime, CAST(FLOOR(CAST(#dt AS FLOAT)) as DATETIME) as OnlyDate

SQL Server 2008 script - how to to acquire current date from system and store it into a date column

Hey fellas, I'm having difficulty obtaining only the date from the system and inserting it into a column, is there a built-in function that can acquire it?
On top of that, how do I add years to the current date?
I know I'm pushing it right now, but I'm also wondering what's the format for the date datatype?
Because sometimes I'd like to manually insert values into a column with that type in mind.
Any help would greatly be appreciated.
Thanks.
To get date only (SQL Server 2008 only) CAST to date type
SELECT CAST(GETDATE() AS date)
To add years, use DATEADD
SELECT DATEADD(year, 2, CAST(GETDATE() AS date))
Formats: use yyyymmdd or ISO yyyy-mm-dd (for newer datetime types) for safety.
Read this for everything about date+time in SQL Server
To add a year to the current date, look at the dateadd() function.
To just get the date from sql w/o the time, you can do this:
DECLARE #Date DATETIME
SELECT #Date = CONVERT(VARCHAR, GETDATE(), 101)
SELECT #Date
Sql will implicity convert the VARCHAR back to DATETIME. Look up the CONVERT function in BOL and it will give you all kinds of different styles for the 3rd parameter.
Bender

Average a time value in SQL Sever 2005

I've got a varchar field in SQL Sever 2005 that's storing a time value in the format "hh:mm"ss.mmmm".
What I really want to do is take the average using the built in aggregate function of those time values. However, this:
SELECT AVG(TimeField) FROM TableWithTimeValues
doesn't work, since (of course) SQL won't average varchars. However, this
SELECT AVG(CAST(TimeField as datetime)) FROM TableWithTimeValues
also doesn't work. As near as I can tell, SQL doesn't know how to convert a value with only time and no date into a datetime field. I've tried a wide variety of things to get SQL to turn that field into a datetime, but so far, no luck.
Can anyone suggest a better way?
SQL Server can convert a time-only portion of a datetime value from string to datetime, however in your example, you have a precision of 4 decimal places. SQL Server 2005 only recognizes 3 places. Therefore, you will need to truncate the right-most character:
create table #TableWithTimeValues
(
TimeField varchar(13) not null
)
insert into #TableWithTimeValues
select '04:00:00.0000'
union all
select '05:00:00.0000'
union all
select '06:00:00.0000'
SELECT CAST(TimeField as datetime) FROM #TableWithTimeValues
--Msg 241, Level 16, State 1, Line 1
--Conversion failed when converting datetime from character string.
SELECT CAST(LEFT(TimeField, 12) as datetime) FROM #TableWithTimeValues
--Success!
This will convert valid values into a DATETIME starting on 1900-01-01. SQL Server calculates dates based on 1 day = 1 (integer). Portions of days are then portions of the value 1 (i.e. noon is 0.5). Because a date was not specified in the conversion, SQL Server assigned the value of 0 days (1900-01-01), which accommodates our need to average the time portion.
To perform an AVG operation on a DATETIME, you must first convert the DATETIME to a decimal value, perform the aggregation, then cast back. For example
SELECT CAST(AVG(CAST(CAST(LEFT(TimeField, 12) as datetime) AS FLOAT)) AS DATETIME) FROM #TableWithTimeValues
--1900-01-01 05:00:00.000
If you need to store this with an extra decimal place, you can convert the DATETIME to a VARCHAR with time portion only and pad the string back to 13 characters:
SELECT CONVERT(VARCHAR, CAST(AVG(CAST(CAST(LEFT(TimeField, 12) as datetime) AS FLOAT)) AS DATETIME), 114) + '0' FROM #TableWithTimeValues
Try this
AVG(CAST(CAST('1900-01-01 ' + TimeField AS DateTime) AS Float))
You really should store those in a datetime column anyway. Just use a consistent date for that part (1/1/1900 is very common). Then you can just call AVG() and not worry about it.
I used Cadaeic's response to get an answer I was looking for, so I thought I should share the code....
I was looking for a query that would average ALL my times together and give me an overall Turn Around Time for all approvals. Below is a nested statement that gives you the AVG TAT for individual id's and and when nested an overall TAT
SELECT
-- calculates overall TAT for ALL Approvals for specified period of time
-- depending on parameters of query
CONVERT(VARCHAR, CAST(AVG(CAST(CAST(LEFT(Tat_mins, 12) as datetime) AS FLOAT)) AS DATETIME), 108) + '0'
from
(
-- tat is for individual approvals
SELECT
dbo.credit_application.decision_status,
dbo.credit_application.application_id,
cast(dbo.credit_application.data_entry_complete as date) as'Data Entry Date',
cast(dbo.credit_application.decision_date as DATE) as 'Decision Date',
avg(datediff(minute, dbo.credit_application.data_entry_complete, dbo.credit_application.decision_date)) as 'TAT Minutes',
convert (char(5), DateAdd(minute, Datediff(minute,dbo.credit_application.data_entry_complete, dbo.credit_application.decision_date),'00:00:00'),108) as 'TAT_Mins'
FROM dbo.credit_application
where Decision_status not in ('P','N')
group by dbo.credit_application.decision_status,
dbo.credit_application.data_entry_complete,
dbo.credit_application.decision_date
--dbo.credit_application.application_id
)bb
How do you think to average on datetime?
I guess that you need to GROUP BY some period (Hour?), and display Count(*)?
SQL Server stores datetime data as 2 4-byte integers, hence a datetime take 8 bytes. The first is days since the base date and the second is milliseconds since midnight.
You can convert a datetime value to an integer and perform mathematical operations, but the convert only returns the "days" portion of the datetime value e.g. select convert(int,getdate()). It is more difficult to return the "time" portion as an integer.
Is using SQL Server 2008 an option for you? That version has a new dedicated time data type.
Thanks, Andy.
I'd work out the difference between all of the dates and an arbitrary point (01/01/1900), average it and then add it back on to the arbitrary point.

Resources