nvarchar date won't convert to date time

498 Views Asked by At

I can't seem to find an applicable solution to my issue. I am trying to pass through an NVARCHAR date and then convert it. When trying to trouble shoot my issue that I am getting:

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

Nothing seems to be helping so far. I tried several suggestions around google and on SO but I keep getting the above message. I tried this suggestion from SO but that also didn't seem to help.

   DECLARE @ConvertCancelDate DATETIME
    DECLARE @incCancelDate nvarchar
    SET @incCancelDate = '2018-07-04'

    -- need to convert the cancel date from nvarchar to datetime
    SET @ConvertCancelDate =  CONVERT(DATETIME, @incCancelDate)
2

There are 2 best solutions below

2
On BEST ANSWER

The problem is you aren't giving the @incCancelDate a size, so it assumes its a single character string.

Change this:

DECLARE @incCancelDate nvarchar

To:

DECLARE @incCancelDate nvarchar(10)
0
On

You're having a problem because you didn't define the length for your @incCancelDate variable, which means it is nvarchar(1).

To see this, try this:

DECLARE @incCancelDate NVARCHAR;
SET @incCancelDate = N'2018-07-04';
SELECT @incCancelDate;

To fix it, do this:

DECLARE @ConvertCancelDate DATETIME;
DECLARE @incCancelDate NVARCHAR(10);
SET @incCancelDate = N'2018-07-04';

-- need to convert the cancel date from nvarchar to datetime
SET @ConvertCancelDate = CONVERT(DATETIME, @incCancelDate, 111);