HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Can SQL Server be configured to not silently truncate VARCHAR values?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
canvaluessqlvarchartruncateserversilentlynotconfigured

Problem

In some scenarios like this one, SQL Server will silently truncate (N)VARCHAR values leading to serious data loss when incorrectly declaring variables.

Question: Can SQL Server be configured to not silently truncate VARCHAR values? (and issue an error/raise an exception instead)

Solution

No there's no way to change this behavior. But this truncation only happens with variable and parameter assignments, not table inserts.

EG

declare @str varchar(8) = 'some very long string'


will be silently truncated

but an insert:

create table #t(a varchar(8))
insert into #t(a) values('some very long string')


will fail with

Msg 8152, Level 16, State 14, Line 7
String or binary data would be truncated.


This is a consequence of TSQL's permissive use of implicit conversions, which is convenient in many cases, but sometimes troublesome.

Code Snippets

declare @str varchar(8) = 'some very long string'
create table #t(a varchar(8))
insert into #t(a) values('some very long string')
Msg 8152, Level 16, State 14, Line 7
String or binary data would be truncated.

Context

StackExchange Database Administrators Q#195146, answer score: 8

Revisions (0)

No revisions yet.