Why would YEAR fail with a conversion error from a Date?

后端 未结 1 1059
星月不相逢
星月不相逢 2021-01-25 13:35

I got a view named \'FechasFirmaHorometros\' defined as

SELECT IdFormulario, 
       CONVERT(Date, RValues) AS FechaFirma 
FROM   dbo.Respuestas 
WHERE  ( IdPreg         


        
相关标签:
1条回答
  • 2021-01-25 14:04

    I assume that RValues is a string column of some type, for some reason. You should fix that and store date data using a date data type (obviously in a separate column than this mixed bag).

    If you can't fix that, then you can prevent what Damien described above by:

    CASE WHEN ISDATE(RValues) = 1 THEN CONVERT(Date, RValues) END AS FechaFirma 
    

    (Which will make the "date" NULL if SQL Server can't figure out how to convert it to a date.)

    You can't prevent this simply by adding a WHERE clause, because SQL Server will often try to attempt the conversion in the SELECT list before performing the filter (all depends on the plan). You also can't force the order of operations by using a subquery, CTE, join order hints, etc. There is an open Connect item about this issue - they are "aware of it" and "hope to address it in a future version."

    Short of a CASE expression, which forces SQL Server to evaluate the ISDATE() result before attempting to convert (as long as no aggregates are present in any of the branches), you could:

    • dump the filtered results into a #temp table, and then subsequently select from that #temp table, and only apply the convert then.
    • just return the string, and treat it as a date on the client, and pull YEAR/MONTH etc. parts out of it there
    • just use string manipulation to pull YEAR = LEFT(col,4) etc.
    • use TRY_CONVERT() since I just noticed you're on SQL Server 2012:

      TRY_CONVERT(DATE, RValues) AS FechaFirma
      
    0 讨论(0)
提交回复
热议问题