Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to cast datetime2 as datetime

Tags:

sql

datetime

ssis

I'm trying to convert datetime2 to datetime in order to create a standard between different sources using only SQL or SSIS Take the following SQL query as example:

SELECT CAST(offer_start_date AS timestamp)
FROM [ODS].[macaclient_offers]

I get the following error: 'Explicit conversion from data type datetime2 to timestamp is not allowed.'

Furthermore, I did managed to convert datetime2 into date using a simple cast.

What is the right way to convert datetime2 to datetime using SQL Server 2008 or SSIS?

gilibi

like image 510
gilibi Avatar asked Jun 18 '12 11:06

gilibi


People also ask

Can you cast date to datetime?

We can convert the Date into Datetime in two ways. Using CONVERT() function: Convert means to change the form or value of something. The CONVERT() function in the SQL server is used to convert a value of one type to another type. Convert() function is used to convert a value of any type to another datatype.

Does Datetime2 have timezone?

To provide an answer, in short Neither Datetime nor Datetime2 encodes timezone information, only the raw date/time data specified.

What is Datetime2 vs datetime?

SQL Server Datetime vs Datetime2 PrecisionThe Datetime2 data type in SQL Server has a precision of 1⁄10000000 of a second, which means we can store 0.0000001 seconds as the smallest unit of time. Whereas, Datetime has a 1/300 second precision, and . 003 second is the smallest unit of time that can be stored.


3 Answers

You are casting to timestamp in your code. Change to datetime.

SELECT CAST(offer_start_date AS datetime) FROM [ODS].[macaclient_offers]
like image 77
Mikael Eriksson Avatar answered Oct 21 '22 07:10

Mikael Eriksson


Your sample select statement is trying to cast offer_start_date to timestamp not datetime.

If you do want a timestamp value from your datetime2 column you could the DatePart function to retrieve parts of the date and build it up yourself.

For example:

declare @date datetime2
set @date = GETUTCDATE()

select @date,
       DATEPART(hour, @date),
       DATEPART(minute, @date),
       DATEPART(second, @date)

MSDN reference to DatePart function.

Not sure why you're getting that error, I've not had the same issue. Example below works fine in my 2008 Management Studio.

create table #temp
(
    OrderId int,
    OrderDate datetime2
)

insert into #temp
(OrderId, OrderDate)
values
(1, GetUTCDate())

select *, CAST(OrderDate as datetime)
from #temp

drop table #temp
like image 3
Mike Avatar answered Oct 21 '22 09:10

Mike


In my case the value was a varchar.

If the value is a varchar of datetime2, like '2018-10-24 12:06:29.6112233', then first cast it to a datetime2 and then to a datetime:

select cast(cast('2018-10-24 12:06:29.6112233' as datetime2) as datetime)
like image 2
CodingYoshi Avatar answered Oct 21 '22 09:10

CodingYoshi