SQL Convert data time format (yyyy-mm-dd 00:00:00.000) to yyyymmdd as int - sql

It must be very simple, but I don't know SQL language very well.
I need to filter data by date which is in this format:
How to do it right to filter data this way?
FROM [TableName] where
FileDate>=20220505
I've already tried the command LEFT and CAST but with no success

Something like this may work:
declare #now Datetime = getdate();
declare #intNow int = cast(cast(datepart(year, #now) as varchar(4)) + RIGHT('00'+CAST(datepart(month, #now) AS VARCHAR(2)),2) + RIGHT('00'+CAST(datepart(day, #now) AS VARCHAR(2)),2) as int)
Although if you have your date to check against in the right format e.g. using:
declare #dateToCheck Datetime = cast(cast(20220505 as varchar) as datetime)
And then
FileDate>= #dateToCheck
it should work

You can create an integer representation of your datetime by multiplying and adding the date parts:
year * 10000 20220000
month * 100 500
day 5
-------------------------
20220505
...
FROM [TableName]
WHERE (DATEPART(year, [FileDate]) * 10000) + (DATEPART(month, [FileDate]) * 100) + (DATEPART(day, [FileDate])) >= 20220505
However I'd still look into fixing the condition input format instead.
Credit to #Rangani in Yesterday's date in SSIS package setting in variable through expression for "multiply and add instead of string concat" trick

Related

Convert day + time string to time

I want to convert a column containing day hour minute and second to time (01 03:08:09) in SQL Server 2014 because it is in the nvarchar(255) data type, so that I can use the DATEDIFF function and I get an error message:
Conversion failed when converting date and/or time from character string.
I tried using;
SELECT CAST (Driver_at_restaurant_datetime AS time)
FROM deliveries
How do I resolve this?
01 03:08:09 is not a valid time, so it will produce an error. You need to extract 03:08:09 first with right() then convert it to a time as follows:
SELECT CAST (right(Driver_at_restaurant_datetime,8) AS time(0))
FROM deliveries
CONVERT(DATETIME,'1900-01-' + CONVERT(CHAR(2),CAST (LEFT(Driver_at_restaurant,2) AS INT) + 1) + RIGHT(Driver_at_restaurant,9),120)
This will convert your string to datetime and will let you apply datediff without loosing the "days" part.
The above implements ODBC cannonical style for convertion. More here:
https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver16
EDIT
Here's a more comprehensive example:
declare #testString1 nvarchar(30) = '00 17:47:12';
declare #testString2 nvarchar(30) = '01 03:08:09';
declare #testDate1 Datetime = CONVERT(DATETIME,'1900-01-' + CONVERT(CHAR(2),CAST (LEFT(#testString1,2) AS INT) + 1) + RIGHT(#testString1,9),120)
declare #testDate2 Datetime = CONVERT(DATETIME,'1900-01-' + CONVERT(CHAR(2),CAST (LEFT(#testString2,2) AS INT) + 1) + RIGHT(#testString2,9),120)
SELECT
#testDate1 AS TestDate1,
#testDate2 AS TestDate1,
DATEDIFF(MINUTE,#testDate1,#testDate2) AS DateDiff_Minutes,
DATEDIFF(HOUR,#testDate1,#testDate2) AS DateDiff_Hours,
DATEDIFF(DAY,#testDate1,#testDate2) AS DateDiff_Days

SQL date conversion HHMMSS.CCCNNNNNN to yyyy-mm-dd hh:mi:ss.mmm

I have data in this format : 114643.052303537 (HHMMSS.CCCNNNNNN).
I need to convert it to this format : 2018-04-25 12:40:59.573 (yyyy-mm-dd hh:mi:ss.mmm), strip of the date part ( i.e. 2018-04-25 ) and calculate the time difference between two formats.
Could you please help with this?
I need the time difference in hh:mi:ss.mmm format
The way to get this is to convert BOTH values to milliseconds (looking at only the time portion for the value that has a date); calculate the difference with simple subtraction, and then convert the result to hh:mi:ss.mmm with division and modulo operations.
declare #dt datetime = '2018-04-25 12:40:59.573'
declare #dunno varchar(16) = '114643.052303537'
Strip the date off the datetime and give it today's date
getdate() + right(convert(varchar,#dt,113),12)
Convert the varchar to time and give it today's date
getdate() + left(stuff(stuff(#dunno,3,0,':'),6,0,':'),8)
Find the milliseconds between them
datediff(millisecond,getdate() + left(stuff(stuff(#dunno,3,0,':'),6,0,':'),8),getdate() + right(convert(varchar,#dt,113),12))
Put it all together in your format
select
convert(char(13),
dateadd(millisecond,
datediff(millisecond,getdate() + left(stuff(stuff(#dunno,3,0,':'),6,0,':'),8),getdate() + right(convert(varchar,#dt,113),12)),
'01/01/00'),
14)
Depending on the speed of your server and other code, it'd be wise to use a variable for GETDATE() at the beginning to prevent millisecond, or even second differences during conversion.
declare #dt datetime = '2018-04-25 12:40:59.573'
declare #dunno varchar(16) = '114643.052303537'
declare #today datetime = getdate()
declare #dunno2 datetime
declare #dt2 datetime
set #dt2 = #today + right(convert(varchar,#dt,113),12)
set #dunno2 = #today + left(stuff(stuff(#dunno,3,0,':'),6,0,':'),8)
select
convert(char(13),
dateadd(millisecond,
datediff(millisecond,#dunno2,#dt2),
'01/01/00'),
14)

Convert datetime to numeric

I am trying to take a date which is in a varchar column in a table, add 1 day to it, and set it as the value of a datetime variable. This is part of a process that runs daily and I need to make sure the day resets to one at the end of the month. Or at the end of the year it doesn't increase from 151231 to 151232. The problem I am having is converting #Date back to numeric in the form YYMMDD. For example VIRN_CHK = '151231', #Date as written below is 'Jan 1 2016 12:00AM'. I need to convert it to 160101 so I can save it in a column in another table of type numeric(6,0).
DECLARE #Date as datetime
set #Date = convert(varchar,dateadd(d, 1,(select top(1) VIRN_CHK from STAGE_INST)))
update cdcdatei
set OT_DATE = #Date
This will work by rebuilding the string format
SELECT RIGHT(YEAR('2015-11-01'),2)
+ RIGHT('00' + CAST(MONTH('2015-11-01') AS VARCHAR(2)),2)
+ RIGHT('00' + CAST(DAY('2015-11-01') AS VARCHAR(2)),2)
So you need to extract the year, month and day numbers from the date? You can to that using DATEPART
DATEPART(yy,dateadd) AS DateYear,
DATEPART(mm,dateadd) AS DateMonth,
DATEPART(dd,dateadd) AS DateDay
then you can multiply and sum them to obtain what you need
VIRN_CHK = DateDay + DateMont * 100 + DateYear * 10000

Combining (concatenating) date and time into a datetime

Using SQL Server 2008, this query works great:
select CAST(CollectionDate as DATE), CAST(CollectionTime as TIME)
from field
Gives me two columns like this:
2013-01-25 18:53:00.0000000
2013-01-25 18:53:00.0000000
2013-01-25 18:53:00.0000000
2013-01-25 18:53:00.0000000
.
.
.
I'm trying to combine them into a single datetime using the plus sign, like this:
select CAST(CollectionDate as DATE) + CAST(CollectionTime as TIME)
from field
I've looked on about ten web sites, including answers on this site (like this one), and they all seem to agree that the plus sign should work but I get the error:
Msg 8117, Level 16, State 1, Line 1
Operand data type date is invalid for add operator.
All fields are non-zero and non-null. I've also tried the CONVERT function and tried to cast these results as varchars, same problem. This can't be as hard as I'm making it.
Can somebody tell me why this doesn't work? Thanks for any help.
Assuming the underlying data types are date/time/datetime types:
SELECT CONVERT(DATETIME, CONVERT(CHAR(8), CollectionDate, 112)
+ ' ' + CONVERT(CHAR(8), CollectionTime, 108))
FROM dbo.whatever;
This will convert CollectionDate and CollectionTime to char sequences, combine them, and then convert them to a datetime.
The parameters to CONVERT are data_type, expression and the optional style (see syntax documentation).
The date and time style value 112 converts to an ISO yyyymmdd format. The style value 108 converts to hh:mi:ss format. Evidently both are 8 characters long which is why the data_type is CHAR(8) for both.
The resulting combined char sequence is in format yyyymmdd hh:mi:ss and then converted to a datetime.
The simple solution
SELECT CAST(CollectionDate as DATETIME) + CAST(CollectionTime as DATETIME)
FROM field
An easier solution (tested on SQL Server 2014 SP1 CU6)
Code:
DECLARE #Date date = SYSDATETIME();
DECLARE #Time time(0) = SYSDATETIME();
SELECT CAST(CONCAT(#Date, ' ', #Time) AS datetime2(0));
This would also work given a table with a specific date and a specific time field. I use this method frequently given that we have vendor data that uses date and time in two separate fields.
Cast it to datetime instead:
select CAST(CollectionDate as DATETIME) + CAST(CollectionTime as TIME)
from field
This works on SQL Server 2008 R2.
If for some reason you wanted to make sure the first part doesn't have a time component, first cast the field to date, then back to datetime.
DECLARE #ADate Date, #ATime Time, #ADateTime Datetime
SELECT #ADate = '2010-02-20', #ATime = '18:53:00.0000000'
SET #ADateTime = CAST (
CONVERT(Varchar(10), #ADate, 112) + ' ' +
CONVERT(Varchar(8), #ATime) AS DateTime)
SELECT #ADateTime [A nice datetime :)]
This will render you a valid result.
Solution (1): datetime arithmetic
Given #myDate, which can be anything that can be cast as a DATE, and #myTime, which can be anything that can be cast as a TIME, starting SQL Server 2014+ this works fine and does not involve string manipulation:
CAST(CAST(#myDate as DATE) AS DATETIME) + CAST(CAST(#myTime as TIME) as DATETIME)
You can verify with:
SELECT GETDATE(),
CAST(CAST(GETDATE() as DATE) AS DATETIME) + CAST(CAST(GETDATE() as TIME) as DATETIME)
Solution (2): string manipulation
SELECT GETDATE(),
CONVERT(DATETIME, CONVERT(CHAR(8), GETDATE(), 112) + ' ' + CONVERT(CHAR(8), GETDATE(), 108))
However, solution (1) is not only 2-3x faster than solution (2), it also preserves the microsecond part.
See SQL Fiddle for the solution (1) using date arithmetic vs solution (2) involving string manipulation
Concat date of one column with a time of another column in MySQL.
SELECT CONVERT(concat(CONVERT('dateColumn',DATE),' ',CONVERT('timeColumn', TIME)), DATETIME) AS 'formattedDate' FROM dbs.tableName;
drop table test
create table test(
CollectionDate date NULL,
CollectionTime [time](0) NULL,
CollectionDateTime as (isnull(convert(datetime,CollectionDate)+convert(datetime,CollectionTime),CollectionDate))
-- if CollectionDate is datetime no need to convert it above
)
insert test (CollectionDate, CollectionTime)
values ('2013-12-10', '22:51:19.227'),
('2013-12-10', null),
(null, '22:51:19.227')
select * from test
CollectionDate CollectionTime CollectionDateTime
2013-12-10 22:51:19 2013-12-10 22:51:19.000
2013-12-10 NULL 2013-12-10 00:00:00.000
NULL 22:51:19 NULL
This works in SQL 2008 and 2012 to produce datetime2:
declare #date date = current_timestamp;
declare #time time = current_timestamp;
select
#date as date
,#time as time
,cast(#date as datetime) + cast(#time as datetime) as datetime
,cast(#time as datetime2) as timeAsDateTime2
,dateadd(dayofyear,datepart(dayofyear,#date) - 1,dateadd(year,datepart(year,#date) - 1900,cast(#time as datetime2))) as datetime2;
dealing with dates, dateadd must be used for precision
declare #a DATE = getdate()
declare #b time(7) = getdate()
select #b, #A, GETDATE(), DATEADD(day, DATEDIFF(day, 0, #a), cast(#b as datetime2(0)))
I am using SQL Server 2016 and both myDate and myTime fields are strings. The below tsql statement worked in concatenating them into datetime
select cast((myDate + ' ' + myTime) as datetime) from myTable
SELECT CONVERT(DATETIME, CONVERT(CHAR(8), date, 112) + ' ' + CONVERT(CHAR(8), time, 108))
FROM tablename

Adding two timestamps in SQL

I have two fields in sql date1 varchar(4) and date2 varchar(4). The date format is just HHmm where HH is the hours and mm is the minutes.
Is there anyway in SQL which we can add the two timestamps together and work out how many hours and minutes?
e.g.
date1 = 0230 date2 = 0145 will total 0415
date1 = 0030 date2 = 0035 will total 0105
declare #d1 varchar(4), #d2 varchar(4), #dif int
set #d1 = '0230'
set #d2 = '0145'
set #dif = (CAST(left(#d1, 2) as int) * 60) + (CAST(left(#d2, 2) as int) * 60) + CAST(right(#d1, 2) as int) + CAST(right(#d2, 2) as int)
select RIGHT('00' + cast(floor(#dif / 60) as varchar), 2) + RIGHT('00' + CAST(#dif % 60 as varchar),2)
Not sure these are really timestamps, what not store them as integers?
Anyhow.. not sure there is a mysql function for this.
You can browse: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
Not sure it will offer much help.
If you store them as seconds, then you can simply have mysql add them, otherwise pull them into a script, convert them to seconds, add them together and then convert to a more readable format if desired.
Try this (use time or date time):
select ADDTIME(time1,time2);
In mysql time is of the form
'01:02:03'
and date time is
'2003-12-31 01:02:03'
IF you happen to be using SQL Server you may also be able to use the DATEDIFF function described here: http://msdn.microsoft.com/en-us/library/ms189794.aspx
This will let you get the difference between any part of a datetime value. DATEADD may be of use for this as well depending on how you want to handle it.