• Good article, Nakul, with thorough tests. Thanks for posting.

    One small quibble: ansi_warnings is actually respected inside stored procedures. The behavior you demonstrated occurs because SQL Server doesn't raise errors (regardless of the ansi_warnings setting) when you assign a too-long value to a char/varchar variable - this is true in both ad-hoc queries and stored procedures - and it handles assigning the values of stored procedure & UDF parameters the same way as assigning variables.

    Here's a quick test to see that even with ansi_warnings on, assigning a too-long string to a varchar variable produces no error in ad-hoc SQL:

    set ansi_warnings on

    -- this won't generate an error

    declare @Small varchar(3)

    set @Small = 'Long Text'

    select @Small -- selects 'Lon'

    -- this will generate a "String or binary data would be truncated" error

    declare @test-2 table (

    Small varchar(3)

    )

    insert into @test-2 (

    Small

    )

    values (

    'Long Text'

    )

    So when you declare your stored procedure with a parameter that's the same length as a corresponding column in the table you'll insert/update in, the too-long value gets silently truncated to the length allowed by the parameter (the same as assigning a variable), and then is short enough to fit into the column without an error.

    You're right that you can perform the length checks in the client application code, and in fact that's pretty much necessary if the application wants to present the user with friendly validation messages instead of SQL errors, but you can still use ansi_warnings as a fallback when you're using stored procedures: just declare the sproc's parameters to be one character longer than is allowed in the corresponding columns. Here's an example:

    set ansi_warnings on

    GO

    create procedure dbo.TruncationTest (

    -- the parameter is one character longer than the "Small" column

    @String varchar(4)

    )

    as begin

    declare @test-2 table (

    Small varchar(3)

    )

    insert into @test-2 (

    Small

    )

    values (

    @String

    )

    end

    GO

    -- this will generate a "String or binary data would be truncated" error

    exec dbo.TruncationTest 'Long Text'

    Hope you find that helpful. 🙂