Search code examples
sqlsql-server-2008nvarchardatetime-conversion

Conversion error when converting 'nvarchar' to 'datetime' in sql server


I have this code :

DECLARE @StartDate nvarchar
SET @StartDate='22/10/2014'
SELECT CAST (@StartDate as datetime)

And it gives me this error:

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

Can anyone suggest a better way/at least no error way to do this.


Solution

  • To convert the string which represents to date in format dd/mm/yyyy you can use this:

    DECLARE @StartDate nvarchar(10)
    SET @StartDate='22/10/2014'     
    SELECT CONVERT(datetime, @StartDate, 103)
    

    Declaring varchar means setting the length to 1.