sql-serverdatetime-formatsql-convert

nvarchar date won't convert to date time


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)

Solution

  • 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)