I have found a scenario where I have a temp table with a varchar(20)
column, and I want to validate the the length of a string when it's being updated.
CREATE TABLE #tmpTest
(
code1 VARCHAR(20)
)
This code causes a
data will be truncated
error:
DECLARE @CODE VARCHAR(10) = '0123456789';
UPDATE #tmpTest
SET code1 = '0123456789' + '/' + @CODE -- 21 chars
WHERE DATALENGTH('0123456789' + '/' + @CODE) <= 20;
Whereas:
DECLARE @CODE VARCHAR(10) = '0123456789';
IF DATALENGTH('0123456789' + '/' + @CODE) <= 20
BEGIN
UPDATE #tmpTest
SET code1 = '0123456789' + '/' + @CODE -- 21 chars
END
and
DECLARE @CODE VARCHAR(10) = '0123456789';
UPDATE #tmpTest
SET code1 = CASE
WHEN DATALENGTH('0123456789' + '/' + @CODE) <= 20
THEN '0123456789' + '/' + @CODE
END
Do not throw this error.
I'm curious to understand why this is happening. Is this something to do with the compiler / optimiser, or am I doing something wrong?