sqlsql-servert-sql

Error when running SQL stored procedure coversion failed when converting date and/or time from character string


DECLARE @i varchar(13)
DECLARE @Year varchar(30)

SET @i = 2
SET @Year = 2013

SELECT SUM(CAST([totalAfterMultiplier] as money)) as 'totalAfterMultiplier' FROM [postfinanceAfterMultiplier] 
                    WHERE CAST([ORDER] as date) >= '01/'+@i+'/'+ @Year +'' AND CAST([ORDER] as date) <= '31/'+@i+'/'+ @Year +''

I am getting this error: Conversion failed when converting date and/or time from character string.

All values in the database are varchar(50)

I have looked at the other posts and can't seem to get it working

Thank you all for your help


Solution

    1. Don't store dates as varchar.
    2. if you want to convert to date from string 'dd/mm/yyyy', use explicit format 103, like select convert(date, '01/12/2013', 103). See other formats here - CAST and CONVERT (Transact-SQL)