String or binary data would be truncated: Error not caught by TRY_CAST

前端 未结 1 1158
不知归路
不知归路 2021-01-22 23:14

The query below...

SELECT YEAR(TRY_CAST(m.MetaValue AS DATE))
FROM MetaData m

...results in this error:

String or binary data w         


        
相关标签:
1条回答
  • 2021-01-22 23:51

    You get this issue if MetaValue is > 8,000 bytes. It throws an error not caught by the TRY_CAST.

    A simple demo of this is below (db <> fiddle)

    DECLARE @X NVARCHAR(MAX) = 'X'
    SET @X = REPLICATE(@X, 4001)
    
    SELECT TRY_CAST(@X AS DATE)
    

    In general SQL Server can evaluate expressions out of logical processing order causing the potential for this even if all the ones matching the WHERE MetaKey IN (...) condition are short strings (also warned about here).

    Guarding the TRY_CAST in an additional CASE expression should resolve things in this case

    SELECT CASE WHEN DATALENGTH(m.MetaValue) <8000 THEN YEAR(TRY_CAST(m.MetaValue AS DATE)) END
    FROM MetaData m
    WHERE m.MetaKey IN (...)
    
    0 讨论(0)
提交回复
热议问题