3

I have a function to convert a string to datetime (101) format. But it gives me an error when I convert this value.

2016-03-01 00:00:00.0000000

And the error is

Msg 241, Level 16, State 1, Line 2
Conversion failed when converting date and/or time from character string.

And my function is ..

ALTER FUNCTION [dbo].[ConvertToDate] 
(
    @Value nVarchar(MAX)
)
RETURNS DATETIME
AS
BEGIN
    IF (@Value <> NULL OR @Value <> '')
        BEGIN
            DECLARE @dt DATETIME
            SET @dt = CONVERT(DATETIME,@Value,101)
            --SET @dt = CAST(@Value AS DATETIME(101))
            RETURN @dt
        END

        RETURN NULL

END

What is the problem?

4
  • 3
    Side note: @Value <> NULL. If you compare anything with NULL using <> the result is NULL, and not true or false. The correct way is @Value IS NOT NULL Commented Jun 15, 2015 at 5:22
  • convert in YYYY-MM-DD hh:mm:ss: Commented Jun 15, 2015 at 5:23
  • use datetime2 it can hadle more seconds Commented Jun 15, 2015 at 5:27
  • @ughai valuable information ... Commented Jun 15, 2015 at 5:36

3 Answers 3

3

It is problem your data. It is not converting. Your data should be like this

'2016-03-01 00:00:00.0000000'

But you can change your data like this

'2016-03-01 00:00:00.000'
Sign up to request clarification or add additional context in comments.

2 Comments

how can I change that.. is there any way to convert them
@tarzanbappa if you want to convert then you can use substring like below DECLARE (at)dt VARCHAR(50) ='2016-03-01 00:00:00.0000000' select CAST(SUBSTRING((at)dt,1,16) AS datetime) , but is is not necessary you can directly use datetime2 that is better option
2

Too many zeros in the millisecond part. This works fine

DECLARE @Value nVarchar(MAX)='2016-03-01 00:00:00.000'
SELECT CONVERT(DATETIME,@Value,101)

You can try using LEFT like this

DECLARE @Value nVarchar(MAX)='2016-03-01 00:00:00.000000'
SELECT CONVERT(DATETIME,LEFT(@Value,23),101)

Comments

1
DECLARE @dt VARCHAR(50) ='2016-03-01 00:00:00.000000'

select CAST (@dt AS DATETIME2)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.