Leo
Leo

Reputation: 5235

Formatting Datetime2 in SQL Server

I am trying to format a datetime2 into yyyy-mm-dd hh:mm:ss format.

I have tried the below options:

This is throwing an error:

SELECT CONVERT(datetime2, 120); 

This works fine, but I need the output of type datetime2

SELECT CONVERT(VARCHAR(19), GETDATE(), 120);

How can I achieve this?

Upvotes: 1

Views: 5258

Answers (1)

Ilyes
Ilyes

Reputation: 14928

You are calling the CONVERT() function without specifying the data type to convert to, so in your case SELECT CONVERT(datetime2, 120); SQL Server will try to convert the value 120 to a datetime2 and that's why you get this error (which you don't provide)

Explicit conversion from data type int to datetime2 is not allowed.

To use CONVERT() with date and time styles, you need to pass

CONVERT(<datatype to convert to>, <Value to be converted>, <Style>).

The SYSUTCDATETIME returns a datetime2 you can convert to as

SELECT CONVERT(VARCHAR(20), SYSUTCDATETIME(), 120)
--Change SYSUTCDATETIME() with your column/variable

For what you say

but I need the output of type datetime2

A DATETIME doesn't have a format, it's a binary value, thus you need to convert it to a formatted string. Since you need to return a DATETIME2 then you need to leave it as it is, and do the formatting in presentation layer.

Upvotes: 4

Related Questions