Skip to main content
Incorporated comment; edited tags
Source Link
Paul White
  • 90.3k
  • 30
  • 424
  • 663

I've recently encountered this weird behavior of TRY_CAST function, and I wonder what's going on here. (It feels like bug, but most of such bugs I have encountered in past were actually intentional.)

When I use the function on string column or variable longer than 4000 characters, I get an error: String or binary data would be truncated.

DECLARE @string NVARCHAR(MAX) = REPLICATE('x', 4001); 

SELECT TRY_CAST(@string AS INT);

The weird thing is, when iI take the literal string and put it into the function, it works fine (it returns NULL).

What is happening here?

I am parsing through a history table, so I need to be able to consume all kinds of strings (and look something up for integer values).

I've recently encountered this weird behavior of TRY_CAST function, and I wonder what's going on here. (It feels like bug, but most of such bugs I have encountered in past were actually intentional.)

When I use the function on string column or variable longer than 4000 characters, I get an error: String or binary data would be truncated.

DECLARE @string NVARCHAR(MAX) = REPLICATE('x', 4001); 

SELECT TRY_CAST(@string AS INT);

The weird thing is, when i take the literal string and put it into the function, it works fine (it returns NULL).

What is happening here?

I've recently encountered this weird behavior of TRY_CAST function, and I wonder what's going on here. (It feels like bug, but most of such bugs I have encountered in past were actually intentional.)

When I use the function on string column or variable longer than 4000 characters, I get an error: String or binary data would be truncated.

DECLARE @string NVARCHAR(MAX) = REPLICATE('x', 4001); 

SELECT TRY_CAST(@string AS INT);

The weird thing is, when I take the literal string and put it into the function, it works fine (it returns NULL).

What is happening here?

I am parsing through a history table, so I need to be able to consume all kinds of strings (and look something up for integer values).

Source Link
J. Doe
  • 140
  • 4

TRY_CAST fails when fed very long string... but only from column or variable

I've recently encountered this weird behavior of TRY_CAST function, and I wonder what's going on here. (It feels like bug, but most of such bugs I have encountered in past were actually intentional.)

When I use the function on string column or variable longer than 4000 characters, I get an error: String or binary data would be truncated.

DECLARE @string NVARCHAR(MAX) = REPLICATE('x', 4001); 

SELECT TRY_CAST(@string AS INT);

The weird thing is, when i take the literal string and put it into the function, it works fine (it returns NULL).

What is happening here?