0

Write simple this query:

select cast('2020-10-10 07:30:00.0000000' as datetime) 

and want to show

'2020-10-10 07:30:00'

but SQL Server return this error:

Conversion failed when converting date and/or time from character string.

How can solve that problem? Thanks.

1
  • According to the documentation learn.microsoft.com/en-us/sql/t-sql/data-types/…, For datetime, the valid time ranges 00:00:00 through 23:59:59.997 . What you want as 07:30:00 is just presentation issue. Do the formatting at your front end application Commented Dec 16, 2020 at 5:57

1 Answer 1

3

A datetime doesn't have that level of precision, instead use datetime2:

select cast('2020-10-10 07:30:00.0000000' as datetime2); 

And to only show the desired string, cast it to a shorter string:

select cast(cast('2020-10-10 07:30:00.0000000' as datetime2) as varchar(19)); 

Obviously it makes no sense to cast a string to date and back again, but I assume you have simplified your actual use-case. Otherwise you could use:

select cast('2020-10-10 07:30:00.0000000' as varchar(19)); 
Sign up to request clarification or add additional context in comments.

1 Comment

thanks your code work,i accept your answer soon

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.