简体   繁体   中英

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

I wrote a procedure which actually searches a record. when i execute it, it gives an error which says:

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

Statement:

((CONVERT(varchar, DATEPART(YYYY, Tbl_Contract.ContractDate), 101)) = @Year or @Year = '')

It appears that you are converting the date to a year value :

DATEPART(YYYY,@ContractDate)

and then trying to convert that back to a date :

CONVERT(varchar, DATEPART(YYYY, @ContractDate),101)

You might try this : EDIT

datepart(yyyy, CONVERT(datetime, @ContractDate))

Since ContractDate is a Varchar you can either parse directly with

SubString(ContractDate, x, 4) = @YearString 

or you can encapsulate the condition

Case when IsDate(ContractDate) = 1 
      then ((CONVERT(varchar, DATEPART(YYYY, @a), 101))) 
      else NULL 
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM