Converting string to datetimeoffset in SQL Server and Postgresql - sql-server

In SQL server I have a column that stores dates of this format:
2017-06-22T00:43:15+0300
as strings.
What I'm trying to do is cast these strings into actual datatimeoffset data in order to handle them as dates.
So far I have found multiple function for converting from datetimeoffset to other timestamp formats but none of these refer to strings.
https://learn.microsoft.com/en-us/sql/t-sql/data-types/datetimeoffset-transact-sql
Exactly the same problem arises on a postgresql database. The best I have managed to achieve so far is just truncate the timezone and convert the rest of the string into timestamp. Ideally, I would like not to use such a lossy transformation.

Time Zone Offset in Sql Server is represented like this
[+|-] hh:mm:
In your data semicolon is missing in the offset part
DECLARE #stringtime VARCHAR(100)= '2017-06-22T00:43:15+0300'
SET #stringtime = Reverse(Stuff(Reverse(#stringtime), 3, 0, ':'))
SELECT Cast(#stringtime AS DATETIMEOFFSET(4))
Result : 2017-06-22 00:43:15.0000 +03:00

Postgres :
to_timestamp('2017-06-22T00:43:15+0300', 'YYYY-MM-DD HH24:MI:SS')
you can try using that postgres function.

Related

SQL Server date formatting issue

I have a SQL Server 2008 database with a transaction table. There is a field defined as NVARCHAR(16). The data stored is date and time formatted like this:
2016100708593100
I need to write a query that looks at that field and pulls data between two dates
select ... from...where convert(varchar,
convert(datetime,left(a.xact_dati,8)),101)
between '9/29/2016' and '10/05/2016'
I have tried other converts but nothing returns any data. If I use >=getdate()-1
I get data so I should be seeing something returned. Any suggestions?
Replace WHERE Clause with
... WHERE CONVERT(DATETIME,LEFT(a.xact_dati,8)) BETWEEN '9/29/2016' AND '10/05/2016'
Assuming YMD order just
where cast(left('2016100708593100', 8) as date) between '20160929' and '20161005'
Note this clause is not satisfied.
The problem is you're trying to do a date comparison with varchar data.
You go half way to converting the initial value to datetime but then back to varchar.
You could rely on Sql to implicitly convert the between parameters to datetime.
select 'matched',convert(datetime,left('2016100708593100',8),112)
where convert(datetime,left('2016100708593100',8),112) between '2016/09/29' and '2016/10/10'
Take the date part of the string and CAST it as DATE and then compare it with the proper date format.
select ... from...
where cast(left('2016100708593100', 8) as date) between '2016-09-29' and '2016-10-10'
a very straight and fast approach could be to keep this in BIGINT
Something like this:
cast(left(a.xact_dati,8) as bigint) between 20160929 and 20161005
But anyway this will not be sargable and therefore cannot use an index.
You might even stick to varchar, as the YYYYMMDD format is safe with alphanumerical sorting. Cutting a string with LEFT is sargable (AFAIK):
left(a.xact_dati,8) between '20160929' and '20161005'

Convert from 'YYYYMMDD' format to to SQL Datetime2

I have an issue concerning conversion in SSIS.
I'm trying to convert StartDATE from DT_WSTR to Datetime2 (for SQL Server)
My date originaly looks like this 20140804 but I need to convert it to Datetime2 in such format 2014-08-04 00:00:00.0000000.
What I've done earlier with the StartDATE Column is:
RTRIM(DATSTHYRA)
Since I need to remove blank spaces...
I figured I can use the already Derived Column and add a new expression to convert it to Datetime2 but I'm running into issues and can't really find a topic online that covers my issue.
You can do it in a single step.
Add Derived Column transformation - transform your YYYYMMDD string to YYYY-MM-DD with SUBSTRING functions and then - cast to DT_DBTIMESTAMP2 with scale needed. This would yield an expression like
(DT_DBTIMESTAMP2, 7)(SUBSTRING([StartDATE],1,4) + "-" + SUBSTRING([StartDATE],5,2)
+ "-" + SUBSTRING([StartDATE],7,2))
Then configure Error Output on this Derived Column transformation to capture and handle conversion errors.
In SSIS, you can use data conversion transformation, the data type mapping is database timestamp with precisionin SSIS is for datetime2 in SQL Server.

Date Conversion Issue MS Access to SQL Server

I'm creating a table B from an exisitng table A. In the table A I have a column ValDate which is varchar and contains Date. When I try to create the table B I have a function used in the query as given below and I get a conversion error. Table A contains null values as well.
MS Access:
((DateDiff("d",Date(),format(Replace(Replace([Table A].ValDate,".","/"),"00/00/0000","00:00:00"),"dd/mm/yyyy")))>0)).
Tables were in MS Access and are being migrated to SQL Server 2012.
SQL Server:
((DATEDIFF(day,FORMAT( GETDATE(), 'dd-MM-yyyy', 'en-US' ),FORMAT( ValDate, 'dd-MM-yyyy', 'en-US' ))>0))
or
((DateDiff(day,GETDATE(),Format(Replace(Replace([TableA].[ValidFrom],'.','/'),'00/00/0000','00:00:00'),'dd/mm/yyyy')))
I tried converting the date using several approachs like Convert , Format and Cast but I end up getting error as below.
Msg 8116, Level 16, State 1, Line 1
Argument data type date is invalid for argument 1 of isdate function.
I would really appreciate someone telling me what I'm missing here.
since you have date data in a string field is very likely you have some value that is not valid against your expected date format.
copy the data in a sql server table and then perform check and validation of the content of the string field.
have a look to the function try_convert that can be helpful when checking the content of the string field containing the date values.
when bad data is ruled out you can apply again your formula with (hopefully) a different result.
a better solution would be to create a separate field with appropriate datatype to store date values converted from the string field and apply your logic to that field.

CONVERTING TO_DATE FROM ORACLE TO SQL SERVER

I am migrating my oracle database to SQL Server. I'm in need of some help converting this one line of code in my WHERE clause
TO_DATE(TBL_TMX_ATTEMPT.LSTUPD) > (SYSDATE - '5')
CONVERT(datetime,TBL_TMX_ATTEMPT.LSTUPD) > DATEADD(DAY,-5,GETDATE())
You can do:
WHERE CONVERT(DATETIME,TBL_TMX_ATTEMPT.LSTUPD) > GETDATE()-5
If LSTUPD is already in a datetime, then omit the CONVERT(). No need to run the conversion if it is already IN the right format.
Also keep in mind GETDATE() includes a time stamp. So this is the current date/time - 5 days.
If you want to get 5 days before midnight use this:
WHERE CONVERT(DATETIME,TBL_TMX_ATTEMPT.LSTUPD) > CONVERT(DATETIME,CONVERT(VARCHAR(10),GETDATE(),120))-5
It's important to know what the data type of TBL_TMX_ATTEMPT.LSTUPD is. If it is a VARCHAR2 or other string type (BAD choice for storing dates, btw), you need to take the date formats into consideration when calling CONVERT in SQL Server. Look up the Date/Time Style parameter of the CONVERT function for more info.
CONVERT ( data_type [ ( length ) ] , expression [ , style ] )

Timestamp confusion in SQL Server

I have a TimeStamp (varchar(50),null) column in my SQL Server 2008 table which looks misleading by the name TimeStamp. I mean it appears as if it's a datatype timestamp but it's varchar.
But it has values like 201403240004 which looks like a date. Can I convert it into date and use?
Read online that timestamp is only a sequence of numbers and has nothing to do with date and time.
You can.
Providing that the format is YYYYMMDDHHmm, a simple way to do that would be:
SELECT CONVERT(DATETIME,
SUBSTRING([TimeStamp],1,4)+'-'+SUBSTRING([TimeStamp],5,2)+'-'
+SUBSTRING([TimeStamp],7,2)+' '+SUBSTRING([TimeStamp],9,2)+':'
+SUBSTRING([TimeStamp],11,2)+':00.000')
FROM Table
This will take this "timestamp" and first transform it to SQL-readable datetime string, i.e. for your example it would be 2014-03-24 00:04:00.000. Then, it will be easily converted to datetime.
Yes, your column should be convertible to DATETIME, but you may have to do the converison yourself if CONVERT() does support the format.
I can't tell from you example what the time format really is.
If it is YYYYMMDDHHMM them
SELECT CONVERT(DATETIME,LEFT('201403240004',8),112)
+CONVERT(DATETIME,SUBSTRING('201403240004',9,2)+ ':' + RIGHT('201403240004',2)+':00' ,108)

Resources