Saturday, October 6, 2012

SQL: String or binary data would be truncated

 Sometimes when you write insert or update query and if get this type of exception:
 
"String or binary data would be truncated. The statement has been terminated."

Dont worry I am going to tell you the solution for this.

This error occurs only when you have a table field that is not big enough to store the data you are inserting in the field.

Example:
Let say you have a table Student with following fields:
ID int
Name varchar(10)

Let say we are going to insert a record in this Table using following query:
insert into Student (ID, Name) 
Values(1, "Name with More Than 10 Characters")

If you execute this query you get the above discussed error since the field Name in Student table has capacity for 10 characters only and you are trying to insert a value which is more than 10 characters.

Solution:
There are two solutions for this:

1. Increase the Field capacity big enough to store the values in database.

2. You can truncate the string value which you have been inserting to fit the field capacity in database. I am going to use the above example again with little change:

insert into Student (ID,Name)
Values (1,cast('Name with More Than 10 Characters' as varchar(10)))

The issue with this solution is that the value that gets stored in database will be only 10 characters:
"Name with  "

So its upto you how you want to handle your problem using any of the solution.

 

 
 

No comments:

Post a Comment