SQL Server - add DATE part of DATETIME to TIME part of DATETIME - sql

In SQL Server 2005 I am interrogating some old legacy data and I need to combine the date component of a datetime column with the time component from another column. Here's an example:
DateColumn: 2016-05-09 00:00:00.000
TimeColumn: 1899-12-30 12:26:00.000
I need the end result converted to the following DateTime:
ResultDateTime: 2016-05-09 12:26:00.000
I tried using:
CAST(DateColumn AS DATETIME) + CAST(TimeColumn AS TIME) AS ResultDateTime
But SQL Server 2005 doesn't recognize the type TIME.
Can someone please show me a way of doing that?
Many thanks!

convert the time column to string HH:MM:SS and add to the date column
ResultDatetIme = DateColumn + convert(varchar(10), TimeColumn, 108)

You can just use DATEADD and DATEDIFF, assuming that the time column's date portion is always 30/12/1899:
declare #t table (DateColumn datetime,TimeColumn datetime)
insert into #t(DateColumn,TimeColumn) values
('2016-05-09T00:00:00.000','1899-12-30T12:26:00.000')
select DATEADD(millisecond,DATEDIFF(millisecond,'18991230',TimeColumn),DateColumn)
from #t
Result:
-----------------------
2016-05-09 12:26:00.000

As you can see following data type supported in SQL 2005:
https://msdn.microsoft.com/en-us/library/ms187819(v=sql.90).aspx
Use datetime and smalldatetime, The smalldatetime data type stores dates and times of day with less precision than datetime. The Database Engine stores smalldatetime values as two 2-byte integers. The first 2 bytes store the number of days after January 1, 1900. The other 2 bytes store the number of minutes since midnight.
datetime values are rounded to increments of .000, .003, or .007 seconds, as shown in the following table.
SELECT CAST('2016-05-09 00:00:00.000' AS DATETIME) + CAST('1900-01-01 12:26:00.000' AS smalldatetime) AS ResultDateTime
Result: 2016-05-09 12:26:00.000
So you can use datetime and smalldatetime, hope fully that will work for you.
Let me know if any issue. love to resolve :)

Related

how can i store datetime in the table without time fraction part?

I'm inserting sample call data to the table ContactCallDetail. when I query the data inserted I'm getting datetime in the format yy-mm-dd hh-mm-ss-ff
declare #StartDateTime datetime = convert(varchar, getdate(), 20);
declare #EndDateTime datetime = dateadd(ss,20,#StartDateTime);
INSERT INTO ContactCallDetail values(0,NULL,'+xxxxx545xx77',#StartDateTime,#EndDateTime,0);
GO
select * from ContactCallDetail
SessionID SessionSeqNum originatorID CallingDN StartDateTime EndDateTime Transfer
100000 0 NULL +xxxxx5453xx7 2022-02-28 20:11:34.000 2022-02-28 20:11:54.000 0
I need to store the datetime without fractions part(ff). how can I achieve that? i want to see 2022-02-28 20:11:34 instead of 2022-02-28 20:11:34.000
The datetime data type always stores fractional seconds with a 1/300 second precision. Use datetime2(0) if you don't need fractional seconds. This will also save storage space (2 bytes).
Just to be sure and to add to #DanGuzman 's answer, you need to change the datatype of the StartDateTime and EndDateTime columns in the ContactCallDetail table to datetime2(0).
That will also make it so you don't have to do CONVERT either on the way in or the way out.

Removing millisecond from datetime throwing error

I have this code in SQL Server 2016
SELECT CONVERT (DATETIME, CONVERT(varchar(8), ExpiryDate))
I get this result:
ExpiryDate
------------------------
2020-08-03 00:00:00.000
How can I remove the .000 (the milliseconds part)?
Expected result should be:
2020-08-03 00:00:00
Please help
By not using a datetime, which is accurate to 1/300th of a second. Instead define your value as a datetime2(0), which is accurate to 1 second (due to having a precision of 0 on milliseconds):
SELECT CONVERT(datetime2(0),ExpiryDate)
FROM ...
You are confusing the internal format and the display format. If you want the value formatted in a particular way, then format it explicitly:
select CONVERT(VARCHAR(19), expirydate, 121)
You can add this into the table as a computed column:
alter table t add expirydate_display as (CONVERT(VARCHAR(19), expirydate, 121))

Date is string between hyphens in SQL Server

I have date formats that are as follows:
Date_str
19-12-2007
31-7-2009
3-1-2010
31-11-2009
etc.
I can't do the following:
CONCAT(RIGHT(Date_str,4),SUBSTRING(Date_str,3,3),LEFT(2))
because as you can see above, the dates are not the same length. Is there a way in SQL Server to extract the date as datetime/date?
I also tried
Convert(datetime, Date_str)
but it just threw an error:
The conversion of a varchar data type to a datetime data type resulted
in an out-of-range value.
If 2012+, I would use Try_Convert(). This will return bogus dates as NULL.
Example
Declare #YourTable Table ([Date_str] varchar(50))
Insert Into #YourTable Values
('19-12-2007')
,('31-7-2009')
,('3-1-2010')
,('31-11-2009')
Select *
,try_convert(date,Date_Str,105)
from #YourTable
Returns
Date_str (No column name)
19-12-2007 2007-12-19
31-7-2009 2009-07-31
3-1-2010 2010-01-03
31-11-2009 NULL -- Notice 11/31 is NOT a date
See https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql for date formats
You probably need
CONVERT(DateTime, Date_str, 105)
As I mentioned in the comments, the only realistic solution is to convert that string into a proper date-typed column. The current format doesn't allow date sorting, or search for a range of dates, eg to find entries in the last week, or between one date and the other.
Parsing with CONVERT or TRY_PARSE means that no indexes can be used to speed up queries. Each time :
WHERE CONVERT(Date, Date_str, 105) > '20170101'
is used, the server will have to scan the entire table to convert the data, then filter the rows.
If you can't change the type of the field itself, you can create a persisted computed column that returns the value as a date and add indexes to it. You'll be able to use that column for indexed querying:
alter table SomeTable add date2 as TRY_convert(Actual_Date,date_str,105) PERSISTED
create index IX_SomeTable_ActualDate on SomeTable (Actual_Date)
This will allow you to perform sorting without tricks:
SELECT *
FROM SomeTable
ORDER BY Actual_Date
Or run range queries that take advantage of the IX_SomeTable_ActualDate index:
SELECT *
FROM SomeTable
Where Actual_Date Between DATEADD(d,-7,GETDATE()) AND GETDATE()
If you have 1000 rows, you could get 1000 times better performance.
Existing applications won't even notice the change. Newer queries and applications will be able to take advantage of indexing and sorting
I had a similar problem: my column (<my_date_field>) had date values in the form of
2021-01
2021-02
2021-10
2021-12
and so on, with data type of nvarchar(4000), and I always ran into the Conversion failed when converting date and/or time from character string. error (when trying e.g. CAST(<my_date_field> AS DATE) or CAST(CAST(<my_date_field> AS VARCHAR(7)) AS DATE) etc.)
I was able to convert them to date with the following code:
SELECT
CONVERT(date, <my_date_field> + '-01') AS first_day_of_month
FROM my_table
which resulted in
2021-08-01
2021-07-01
2021-06-01
2021-05-01

can datetime type of sql server hold time only?

I'm trying to store time in format
05:00 PM
in database. but when i insert the data it automatically stores date as well like
2016-07-20 17:00:00.000
All i want only
17:00
in database
You cant store Time only in a datetime field it stores default date,Use TIME data type if you are on 2008..
declare #t datetime
select #t=cast(getdate() as time)
print #t
---Jan 1 1900 9:17AM
declare #t time
select #t=cast(getdate() as time)
print #t
---09:17:48.3330000
for sql 2008
select cast(getdate() as time)
--09:17:25.4400000
for 2005
select convert(varchar(10),getdate(),108)
---09:17:33
your exact format
select cast(datepart(hour,getdate()) as varchar(10))+':'+ cast(datepart(minute,getdate()) as varchar(10))
---9:17
You also can use FORMAT to store only time (From SQl 2012)
select FORMAT(GETDATE(),'HH:MM')
--09:07
First, as suggested in the comments, you should use time type instead of datetime.
The format of time in SQL Server is : hh:mm:ss or hh:mm:ss.nnnnnnn. If you want time to be in AM PM format just use this :
CONVERT(varchar(15),CAST('17:00:00.000' AS TIME),100)

Parsing a time span string in sql

I am reading in from a datasource that is giving me time in a varchar in the format d:h:m:s:f, The day portion is always 0, the column represents a time of day. I would like to add this column to a datetime I already have.
Entry_Date Entry_Time
3/3/2009 12:00:00 0:16:17:6:0
8/24/2011 12:00:00 0:8:39:18:0
9/4/2010 12:00:00 0:12:33:18:0
If I was using C# I would just do TimeSpan.ParseExact but I do not know how to handle this in a purely sql fashion.
I would cast to time but I am using Sql Server 2005 and that does not have the time type.
How would I add the time to the neighboring datetime?
As simple as this:
select Entry_Date + cast(Entry_Time as datetime) combinedCol
from YourTable
Here is a working fiddle: http://sqlfiddle.com/#!3/85c3c/1
Enjoy!
Original Asker's note:
SQL can not handle the fractional seconds however they can be trimed off so the query would be
select Entry_Date + cast(left(Entry_Time, len(Entry_Time) - 2) as datetime) combinedCol
from YourTable