Ошибка error while update execution data truncation

In this SQL Server tutorial, we will understand the “String or binary data would be truncated” error in a SQL Server 2019, and we will also learn how to resolve this error. For this, we will cover the following topics.

  • String or binary data would be truncated SQL Server Error
  • String or binary data would be truncated SQL Server Which Column
  • How to fix “String or binary data would be truncated”
  • String or binary data would be truncated SQL Server 2019
  • String or binary data would be truncated Datetime SQL Server
  • String or binary data would be truncated in SQL Server Stored Procedure

string or binary data would be truncated in sql

Error Message

This error usually occurs when we try to insert more data into a column than the specified column can store. Let’s understand this with the help of an example.

CREATE TABLE Sample (
	id INT,
	Name VARCHAR(10),
	gender VARCHAR(8)
);
insert into Sample (id, Name, gender) values (1, 'Maurits Hessing', 'Agender');

In the example, we are creating a table with 3 columns in it, and for the Name column, we have defined the data type as “VARCHAR(10)“. It means that the Name column can hold a string having 10 characters.

But while inserting a value into the table, we have specified the value for the Name column with 15 characters which is more than 10.

So the above query will return the following error.

string or binary data would be truncated in sql server

Example Result

Read SQL Server bulk insert from CSV file

String or binary data would be truncated SQL Server Which Column

Till now, we have understood the reason why we are getting this error. Now let’s understand how we can find the column due to which we are getting the error.

In SQL Server 2019, Microsoft has updated the error message for this error. For SQL Server 2019, the error message not only returns the column name but also returns the table for which the error has been encountered.

For demonstration, consider the error message that we have shown in the previous section.

string or binary data would be truncated in sql server error

Identifying Column

Now, if we read the error message thoroughly, we will easily get the column name for which the error has been encountered.

If you have upgraded from some previous SQL Server version to SQL Server 2019. Then you might need to execute the following query in the database where you want a complete truncate warning.

ALTER DATABASE SCOPED CONFIGURATION 
SET VERBOSE_TRUNCATION_WARNINGS = ON;

And for SQL Server 2016/2017, we have to turn on the trace flag 460. And to enable the trace flag 460, we can execute the following query while inserting or updated table records.

insert into Sample (id, Name, gender) values (1, 'Maurits Hessing', 'Agender')
OPTION (QUERYTRACEON 460);

Now by enabling the trace flag 460, the SQL Server will return a detailed truncation warning, from which we can easily identify the column name.

Read: Identity Column in SQL Server

How to fix “String or binary data would be truncated”

The main reason behind this error is the more amount of data that we are trying to store in a column than a specific column can store. So a quick solution to solve this error is by increase the column size. For this, we can use the ALTER TABLE command and increase the column size.

For demonstration, consider the following query, used to modify the column size of the sample table.

--Modifying Table
ALTER TABLE Sample
ALTER COLUMN Name VARCHAR(20)
GO

--Inserting the new record
insert into Sample (id, Name, gender) values (1, 'Maurits Hessing', 'Agender')
GO

In the above example, first, we are using the ALTER TABLE and ALTER COLUMN statements to modify the size of the column. After this, we are using the INSERT statement to insert a new record. And if the inserted value is less than or equal to the size of the column, then the new record will be inserted successfully.

string or binary data would be truncated in sql server stored procedure

Successful Insertion

Read: Create Foreign Key in SQL Server

String or binary data would be truncated SQL Server 2019

While using SQL Server earlier versions, if we try to insert more data than specified for a column, we get the following error.

String or binary data would be truncated

Error Message before SQL Server 2019

Now, this error message is not much helpful in debugging the issue. For this, we have to manually check the query to find and resolve the error.

But Microsoft has made some enhancements for this error message in SQL Server 2019. So, in SQL Server 2019, if this error has been encountered, the SQL Server will return a detailed truncate warning.

The column name, table name, even the value for which the error has been raised is mentioned in the error message. The example is already shown in the “String or binary data would be truncated SQL Server Which Column” topic.

If you are already using SQL Server 2019, but still not getting the detailed error message. Then execute the following query in the database where you want a complete truncate warning.

ALTER DATABASE SCOPED CONFIGURATION 
SET VERBOSE_TRUNCATION_WARNINGS = ON;

String or binary data would be truncated Datetime SQL Server

This issue commonly occurs when entering a record into a table with a VARCHAR or CHAR data type column and a value is longer than the column’s length. We will not get this error in the case of a Datetime datatype.

In the case of the DateTime data type, if we try to insert a longer value than the column size then the column will ignore the extra characters and save the value.

Now for demonstration, consider the following example given below.

--Creating table
CREATE TABLE Sample (
	id INT,
	Name VARCHAR(50),
	Joining_date DATETIME
);

--inserting values
insert into Sample (id, Name, Joining_date) values (1, 'Modesty Malley', SYSDATETIME());
  • In the example, we are creating a table named “Sample” with 3 columns.
  • Out of these 3 columns, we have defined the “Joining_date” column to be a DateTime column.
  • Now, the Datetime column has a default fractional precision of 3, which means it can store a maximum of 3 characters in nanoseconds part (yyyy-mm-dd hh:mm:ss:nnn).
  • But while inserting values, we are using the SYSDATETIME() function which returns the current date-time value in Datetime2 format. The SYSDATETIME() will return the date-time value with a fractional seconds precision of 7 (yyyy-mm-dd hh:mm:ss:nnnnnnn).
  • But still, the value got successfully inserted in the Datetime column, but it has ignored the last 4 characters.

String or binary data would be truncated datetime

Inserted Value

Read: Types of Backup in SQL Server

String or binary data would be truncated in SQL Server Stored Procedure

This error can also occur while executing a stored procedure in SQL Server, which is trying to insert new values in a column. But still, the reason behind this error will remain the same i.e, the column length is less than the value length that we are trying to insert.

Let’s understand this with the help of an example. And for this, we are using the following query to create a sample table.

--Creating table
CREATE TABLE Sample (
	id INT,
	Name VARCHAR(5),
	Joining_date DATETIME
);

Now take a look at the Name column, for the Name column we have defined the character length to be 5.

Next, we are using the following stored procedure to insert new records in the sample table.

ALTER PROCEDURE Insert_data
AS
--inserting values
insert into Sample (id, Name, Joining_date) values (1, 'Modesty Malley', GETDATE());

GO

Exec Insert_data

But while inserting the record through the stored procedure, we have specified the name value to be 14 characters. So, if we try to execute this procedure, we will get the following error.

String or binary data would be truncated stored procedure

Error while executing stored procedure

And the simplest solution to resolve this error is by modifying the column and increasing the column length. This solution is already been discussed in the topic above.

You may like the following SQL server tutorials:

  • SQL Server Row_Number
  • SQL Server Add Column + Examples
  • IDENTITY_INSERT in SQL Server
  • SQL Server stored procedure output parameter

So in this SQL Server tutorial, we have learned how to solve the “String or binary data would be truncated” error in a SQL Server, and we have also covered the below topics.

  • String or binary data would be truncated SQL Server Error
  • String or binary data would be truncated SQL Server Which Column
  • How to fix “String or binary data would be truncated”
  • String or binary data would be truncated SQL Server 2019
  • String or binary data would be truncated Datetime SQL Server
  • String or binary data would be truncated in SQL Server Stored Procedure

I am Bijay having more than 15 years of experience in the Software Industry. During this time, I have worked on MariaDB and used it in a lot of projects. Most of our readers are from the United States, Canada, United Kingdom, Australia, New Zealand, etc.

Want to learn MariaDB? Check out all the articles and tutorials that I wrote on MariaDB. Also, I am a Microsoft MVP.


Asked by: Destinee Wuckert

Score: 5/5
(35 votes)

Solution to fix String or binary data truncation

  1. Fix the data that we are trying to insert or update. Data length should not exceed the maximum allowed limit for the particular column.
  2. Use ‘SET ANSI_WARNINGS OFF’ to truncate the data and insert it as per column maximum string length.

What does data truncated mean in SQL?

TRUNCATE TABLE removes all rows from a table, but the table structure and its columns, constraints, indexes, and so on remain. … To remove the table definition in addition to its data, use the DROP TABLE statement.

What does data truncation error mean?

So it means the new incident subjects cannot fit into your varchar(80) in the mirror database. To fix this, either manually alter the mirror table (column) or re-create the whole synchronization and perform an initial data load.

How do I ignore data truncation error in SSIS?

In SSIS, how to ignore Truncation errors in XML source?

  1. double-click on the XML source.
  2. go to the Error output tab.
  3. select a column.
  4. select «Ignore Failure» in the drop-down list that corresponds to the «Truncation».
  5. Click OK.

How do you fix error string or binary data would be truncated?

To fix this error, patch to SQL Server 2016 SP2, CU6 or newer (including SQL Server 2017), and then turn on trace flag 460. You can enable it at the query level or at the server level. First, let’s see the error happen: let’s create a table with small fields, and then try to insert more data than it holds.

34 related questions found

What is truncation error in SQL Server?

We normally call it as silent truncation and occur when we try to insert string data (varchar, nvarchar, char, nchar) into more than the size of the column. If we are dealing with the huge amount of data with lots of columns, if we get any error it becomes difficult to find out which column, data caused the issue.

How do you truncate a string in SQL?

The basic syntax is SUBSTR(string, position, length), where position and length are numbers. For example, start at position 1 in the string countryName, and select 15 characters. Length is optional in MySQL and Oracle, but required in SQL Server.

How do I fix a truncation error in Excel?

So if your package is failing due to a truncation error on a string column, simple way is to add a dummy row as first row in the Excel file with data greater than 255 characters in the column that is causing truncation error.

What is truncation of data?

From Wikipedia, the free encyclopedia. In databases and computer networking data truncation occurs when data or a data stream (such as a file) is stored in a location too short to hold its entire length.

How do I truncate a column in SQL Server?

ALTER TABLE tableName DROP COLUMN columnName ; ALTER TABLE tableName DROP COLUMN columnName ; Example 1: Let us DROP the gender column from our DataFlair_info database. We can see the gender column is no longer available in our database.

What is a truncation error example?

In computing applications, truncation error is the discrepancy that arises from executing a finite number of steps to approximate an infinite process. For example, the infinite series 1/2 + 1/4 + 1/8 + 1/16 + 1/32 … adds up to exactly 1.

How do you reduce discretization error?

Discretization error can usually be reduced by using a more finely spaced lattice, with an increased computational cost.

What is true error?

In general, the true error is the difference between the true value of a quantity and the observed measurement (Muth, 2006). … True error is also sometimes defined as the difference between the true value found by a calculation, and the approximate value found by using a numerical method.

What is difference between truncate and delete command?

Key differences between DELETE and TRUNCATE

The DELETE statement is used when we want to remove some or all of the records from the table, while the TRUNCATE statement will delete entire rows from a table. DELETE is a DML command as it only modifies the table data, whereas the TRUNCATE is a DDL command.

How do you write a delete query?

To create a delete query, click the Create tab, in the Queries group, click Query Design. Double-click each table from which you want to delete records, and then click Close. The table appears as a window in the upper section of the query design grid.

What is truncate command?

SQL Truncate is a data definition language (DDL) command. It removes all rows in a table. SQL Server stores data of a table in the pages. The truncate command deletes rows by deallocating the pages. … At a high level, you can consider truncate command similar to a Delete command without a Where clause.

What is an example of truncation?

Truncation is a searching technique used in databases in which a word ending is replaced by a symbol. … For example: If the truncation symbol is *, then the truncated word, laugh*, will search for results containing laugh, laughter, laughing etc. Note: Placing the truncation symbol too soon in a word should be avoided.

What is truncation effect?

From Wikipedia, the free encyclopedia. In statistics, truncation results in values that are limited above or below, resulting in a truncated sample. A random variable is said to be truncated from below if, for some threshold value , the exact value of is known for all cases , but unknown for all cases .

How do you know if data is censored?

So to summarize, data are censored when we have partial information about the value of a variable—we know it is beyond some boundary, but not how far above or below it. In contrast, data are truncated when the data set does not include observations in the analysis that are beyond a boundary value.

How do I push Excel data into SQL Server?

Our Simple Example

  1. Step 1 – Create a Project. …
  2. Step 2 – Create a Connection to your SQL Server Database. …
  3. Step 3 – Create a Table. …
  4. Step 4 – Create an Excel Connection. …
  5. Step 5 – Create a Data Flow Task. …
  6. Step 6 – Creating the Excel Source. …
  7. Step 7 – Removing Rubbish Data. …
  8. Step 8 – Piping the ‘OK Data’ into a SQL Server Table.

What is import and export data in SQL Server?

The Import and Export wizard in SQL Server Management Studio (SSMS) assists users with copying data from one location to another. The export tasks lets you export data into another database, Excel, text files, etc. and the import tasks let you load data from other databases or sources like Excel, text files, etc.

How do you handle errors in SSIS?

Create SSIS package for error handling

  1. Create SSIS package for error handling. …
  2. Right-click on [Learn Error Handling] task and edit. …
  3. You can notice the three things in the below image: …
  4. Click on a column to verify the data in the source text file and available columns.

How do I get last three characters of a string in SQL?

SQL Server RIGHT() Function

  1. Extract 3 characters from a string (starting from right): SELECT RIGHT(‘SQL Tutorial’, 3) AS ExtractString;
  2. Extract 5 characters from the text in the «CustomerName» column (starting from right): …
  3. Extract 100 characters from a string (starting from right):

How do I get the last character of a string in SQL?

To get the first n characters of string with MySQL, use LEFT(). To get the last n char of string, the RIGHT() method is used in MySQL.

What is the meaning of like 0 0?

Feature ends with two 0’s. Feature has more than two 0’s. Feature has two 0’s in it, at any position.

In this article, we’ll take a look into SQL truncate improvement in SQL Server 2019.

Data inserts and updates are a normal and regular task for the developers and database administrators as well as from the application. The source of the data can be in multiple forms as if direct insert using T-SQL, stored procedures, functions, data import from flat files, SSIS packages etc.

Sometimes we receive the bad data in terms of character limits more than the defined limit in a column. For example, if we want to insert bulk data into a database table using an insert statement, we get a bad data on character length 11 into employee name column while our existing column (Employee_name) allows only 10 characters, so how SQL Server will behave? it will raise an SQL truncate error. Insert statement will fail in this case. We normally call it as silent truncation and occur when we try to insert string data (varchar, nvarchar, char, nchar) into more than the size of the column.

If we are dealing with the huge amount of data with lots of columns, if we get any error it becomes difficult to find out which column, data caused the issue. However, it is important for us to dig out into the data and identify the bad data, fix it in order to import the data. We can use a profiler or extended events to troubleshoot the data insert, update, but again it is a resource and time-consuming. We can also use the custom stored procedure to check the length of the data before inserting into the table, but it is an extra overhead for us. Moreover, if we are getting frequent SQL truncate errors, it might be difficult to troubleshoot using a profiler and extended events in that case. This is the issue developers and DBA used to highlight in a different forum to improve the error related with silent truncation of data so that it can be quickly fixed.

Let us first create a sample database, table and insert some dummy data into it.

Create Database SQLShackDemo

Go

Use SQLShackDemo

Go

CREATE TABLE DemoSQL2019

(

[ID] INT identity(1,1),

[NAME] VARCHAR(10),

)

GO

Example 1

INSERT INTO DemoSQL2019 VALUES (‘SQLShack ApexSQL Community’)

GO

INSERT INTO DemoSQL2019  VALUES (‘Rajendra Gupta Author’)

GO

Create Sample Database and Tables

As we can see above, we get the SQL truncate error message ‘String or binary data would be truncated.’

Therefore, before we move further, let me explain why this error occurred. In below query, we are checking the length of the string that we want to insert into our workload.

select len(‘SQLShack ApexSQL Community’) as [StrringLength]

Select len(‘Rajendra Gupta Author’) as [StrringLength]

Check String length

While using below query, we can check that the Name column in our DemoSQL2019 table allows only 10 characters.

select character_maximum_length,column_name

from information_schema.columns

where table_name = ‘DemoSQL2019’

and Column_name=‘NAME’

Check column maximum allowed character value

As we can see above, SQL truncate error occurred due to the length of the data more than the length of the string allowed in the column.

Example 2

Let us look at the complex data:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

CREATE TABLE [dbo].[Customerstest](

  [CustomerID] [int] NOT NULL,

  [CustomerName] [nvarchar](30) NOT NULL,

  [BillToCustomerID] [int] NOT NULL,

  [CustomerCategoryID] [int] NOT NULL,

  [BuyingGroupID] [int] NULL,

  [PrimaryContactPersonID] [int] NOT NULL,

  [AlternateContactPersonID] [int] NULL,

  [DeliveryMethodID] [int] NOT NULL,

  [DeliveryCityID] [int] NOT NULL,

  [PostalCityID] [int] NOT NULL,

  [CreditLimit] [decimal](18, 2) NULL,

  [AccountOpenedDate] [date] NOT NULL,

  [StandardDiscountPercentage] [decimal](18, 3) NOT NULL,

  [IsStatementSent] [bit] NOT NULL,

  [IsOnCreditHold] [bit] NOT NULL,

  [PaymentDays] [int] NOT NULL,

  [PhoneNumber] [nvarchar](20) NOT NULL,

  [FaxNumber] [nvarchar](20) NOT NULL,

  [DeliveryRun] [nvarchar](5) NULL,

  [RunPosition] [nvarchar](5) NULL,

  [WebsiteURL] [nvarchar](256) NOT NULL,

  [DeliveryAddressLine1] [nvarchar](60) NOT NULL,

  [DeliveryAddressLine2] [nvarchar](60) NULL,

  [DeliveryPostalCode] [nvarchar](10) NOT NULL,

  [DeliveryLocation] [geography] NULL,

  [PostalAddressLine1] [nvarchar](60) NOT NULL,

  [PostalAddressLine2] [nvarchar](60) NULL,

  [PostalPostalCode] [nvarchar](10) NOT NULL,

  [LastEditedBy] [int] NOT NULL,

  [ValidFrom] [datetime2](7) NOT NULL,

  [ValidTo] [datetime2](7) NOT NULL

)

GO

Insert sample data in bulk order

We can notice here that the table involves many columns and we are trying to insert multiple records in our example. Now, we have the same SQL truncate error message, but we did not get any clue about which row is causing the issue. Due to a large number of insert statements, it would be difficult to fix this issue. This is the behavior until SQL Server 2017. Now in below section let us see how SQL Server 2019 solves this issue.

SQL Server 2019 behavior for data truncation

Pre-requisite

Before we explore the SQL Server 2019 solution to the silent data truncation issue, we should have below pre-requisites:

  • Installation of SQL Server 2019 Public preview version.
  • SQL Server Management Studio 18.0 Preview 4

In my previous article, we learned that SQL Server 2019 preview version (SQL Server vNext CTP 2.0) launched recently and you can install it on windows version by following up the SQL Server 2019 overview and installation.

Now let us look at the SQL Server 2019 behavior of this SQL truncate issue. We can see in the database properties, the database compatibility level is set to 150, which is the new compatibility level for SQL Server 2019.

If database compatibility level is other than 150, we can change it using the below query.

ALTER DATABASE database_name SET COMPATIBILITY_LEVEL = 150

SQL Server 2019 Compatibility level 150

Now let us run the query from the example 1 in this SQL Server 2019 Database with compatibility level 150.

Data truncation error

We got a similar error ‘String or binary data would be truncated’. So, do we have the same kind of behavior in SQL Server 2019 as well?

No, SQL Server 2019 gives information that is more useful to fix the issue. We get the below message if the string or binary data is truncated.

String or binary data would be truncated in table ‘%.*ls’, column ‘%.*ls’. Truncated value: ‘%.*ls’.

This error message highlights clearly the table name, column name, and the truncated value in SQL Server 2019. Therefore, we do not worry or troubleshoot to find the problematic data or column giving this error message. This was a real concern for most of the DBA’s and developers and this feature was in demand from a long time.

We can look this message into sys. messages table in SQL Server 2019; message id 2628 contains this SQL truncate error message. We can see the table contains error messages for the same error code in the different language. SQL Server picks up the correct message_id based on the collation setting which is the language id in this table.

Error message id newly intoduced in SQL 2019

While in previous versions till SQL Server 2017, only ‘String or binary data would be truncated’ message is shown

String truncation error message until SQL Server 2017

In SQL Server 2019, we need to enable trace flag 460 using DBCC TraceOn. This trace flag displays the SQL truncate error message – “String or binary data would be truncated in table ‘%.*ls’, column ‘%.*ls’. Truncated value: ‘%.*ls’.”

Let us enable the trace flag 460 and run the query.

New Error message fo data truncation in SQL Server 2019

Now let us run the insert statement from our script in example 2 with DBCC TRACEON(460)Data truncation error SQL Server 2019

Solution to fix String or binary data truncation

Now in SQL Server 2019.we can easily find out the column and data, which caused the issue. In order to fix the issue, we can choose from any of the below solution appropriate to us.

  • Fix the data that we are trying to insert or update. Data length should not exceed the maximum allowed limit for the particular column
  • Use ‘SET ANSI_WARNINGS OFF’ to truncate the data and insert it as per column maximum string length

In the below example used ‘ SET ANSI_WARNINGS off’. Therefore, SQL Server will truncate the data as needed to make it fit into the column. We will not get any SQL truncate error as well since data is truncated and inserted into the table.

We can see the SQL Server inserts data as fit into the column data size. For example, ‘SQLShack ApexSQL Community’ inserted to the table after truncation as ‘SQLShack A’

SET ANSI_WARNINGS off option to insert data

  • Modify the column using the alter table statement

We can also modify the column property to allow more string length data. We can use the below query to alter table.

ALTER TABLE [TableName] ALTER COLUMN [Column_name] datatype(value)

In the below example, we modified the column [CustomerName] to varchar (50) from varchar(30) and executed the example 2 query. This time it executes successfully.

Alter the Column value to allow more characters

Conclusion

Silent data truncation in SQL Server 2019 is a really nice enhancement. This will make many database administrators and developers happy with this detailed SQL truncate error message. Currently, we have to enable the trace flag in SQL Server 2019. I believe this feature will be available without trace flag as well in an upcoming release.

  • Author
  • Recent Posts

Rajendra Gupta

Hi! I am Rajendra Gupta, Database Specialist and Architect, helping organizations implement Microsoft SQL Server, Azure, Couchbase, AWS solutions fast and efficiently, fix related issues, and Performance Tuning with over 14 years of experience.

I am the author of the book «DP-300 Administering Relational Database on Microsoft Azure». I published more than 650 technical articles on MSSQLTips, SQLShack, Quest, CodingSight, and SeveralNines.

I am the creator of one of the biggest free online collections of articles on a single topic, with his 50-part series on SQL Server Always On Availability Groups.

Based on my contribution to the SQL Server community, I have been recognized as the prestigious Best Author of the Year continuously in 2019, 2020, and 2021 (2nd Rank) at SQLShack and the MSSQLTIPS champions award in 2020.

Personal Blog: https://www.dbblogger.com
I am always interested in new challenges so if you need consulting help, reach me at rajendra.gupta16@gmail.com

View all posts by Rajendra Gupta

Rajendra Gupta

In this SQL Server tutorial, we will understand the “String or binary data would be truncated” error in a SQL Server 2019, and we will also learn how to resolve this error. For this, we will cover the following topics.

  • String or binary data would be truncated SQL Server Error
  • String or binary data would be truncated SQL Server Which Column
  • How to fix “String or binary data would be truncated”
  • String or binary data would be truncated SQL Server 2019
  • String or binary data would be truncated Datetime SQL Server
  • String or binary data would be truncated in SQL Server Stored Procedure

string or binary data would be truncated in sql

Error Message

This error usually occurs when we try to insert more data into a column than the specified column can store. Let’s understand this with the help of an example.

CREATE TABLE Sample (
	id INT,
	Name VARCHAR(10),
	gender VARCHAR(8)
);
insert into Sample (id, Name, gender) values (1, 'Maurits Hessing', 'Agender');

In the example, we are creating a table with 3 columns in it, and for the Name column, we have defined the data type as “VARCHAR(10)“. It means that the Name column can hold a string having 10 characters.

But while inserting a value into the table, we have specified the value for the Name column with 15 characters which is more than 10.

So the above query will return the following error.

string or binary data would be truncated in sql server

Example Result

Read SQL Server bulk insert from CSV file

String or binary data would be truncated SQL Server Which Column

Till now, we have understood the reason why we are getting this error. Now let’s understand how we can find the column due to which we are getting the error.

In SQL Server 2019, Microsoft has updated the error message for this error. For SQL Server 2019, the error message not only returns the column name but also returns the table for which the error has been encountered.

For demonstration, consider the error message that we have shown in the previous section.

string or binary data would be truncated in sql server error

Identifying Column

Now, if we read the error message thoroughly, we will easily get the column name for which the error has been encountered.

If you have upgraded from some previous SQL Server version to SQL Server 2019. Then you might need to execute the following query in the database where you want a complete truncate warning.

ALTER DATABASE SCOPED CONFIGURATION 
SET VERBOSE_TRUNCATION_WARNINGS = ON;

And for SQL Server 2016/2017, we have to turn on the trace flag 460. And to enable the trace flag 460, we can execute the following query while inserting or updated table records.

insert into Sample (id, Name, gender) values (1, 'Maurits Hessing', 'Agender')
OPTION (QUERYTRACEON 460);

Now by enabling the trace flag 460, the SQL Server will return a detailed truncation warning, from which we can easily identify the column name.

Read: Identity Column in SQL Server

How to fix “String or binary data would be truncated”

The main reason behind this error is the more amount of data that we are trying to store in a column than a specific column can store. So a quick solution to solve this error is by increase the column size. For this, we can use the ALTER TABLE command and increase the column size.

For demonstration, consider the following query, used to modify the column size of the sample table.

--Modifying Table
ALTER TABLE Sample
ALTER COLUMN Name VARCHAR(20)
GO

--Inserting the new record
insert into Sample (id, Name, gender) values (1, 'Maurits Hessing', 'Agender')
GO

In the above example, first, we are using the ALTER TABLE and ALTER COLUMN statements to modify the size of the column. After this, we are using the INSERT statement to insert a new record. And if the inserted value is less than or equal to the size of the column, then the new record will be inserted successfully.

string or binary data would be truncated in sql server stored procedure

Successful Insertion

Read: Create Foreign Key in SQL Server

String or binary data would be truncated SQL Server 2019

While using SQL Server earlier versions, if we try to insert more data than specified for a column, we get the following error.

String or binary data would be truncated

Error Message before SQL Server 2019

Now, this error message is not much helpful in debugging the issue. For this, we have to manually check the query to find and resolve the error.

But Microsoft has made some enhancements for this error message in SQL Server 2019. So, in SQL Server 2019, if this error has been encountered, the SQL Server will return a detailed truncate warning.

The column name, table name, even the value for which the error has been raised is mentioned in the error message. The example is already shown in the “String or binary data would be truncated SQL Server Which Column” topic.

If you are already using SQL Server 2019, but still not getting the detailed error message. Then execute the following query in the database where you want a complete truncate warning.

ALTER DATABASE SCOPED CONFIGURATION 
SET VERBOSE_TRUNCATION_WARNINGS = ON;

String or binary data would be truncated Datetime SQL Server

This issue commonly occurs when entering a record into a table with a VARCHAR or CHAR data type column and a value is longer than the column’s length. We will not get this error in the case of a Datetime datatype.

In the case of the DateTime data type, if we try to insert a longer value than the column size then the column will ignore the extra characters and save the value.

Now for demonstration, consider the following example given below.

--Creating table
CREATE TABLE Sample (
	id INT,
	Name VARCHAR(50),
	Joining_date DATETIME
);

--inserting values
insert into Sample (id, Name, Joining_date) values (1, 'Modesty Malley', SYSDATETIME());
  • In the example, we are creating a table named “Sample” with 3 columns.
  • Out of these 3 columns, we have defined the “Joining_date” column to be a DateTime column.
  • Now, the Datetime column has a default fractional precision of 3, which means it can store a maximum of 3 characters in nanoseconds part (yyyy-mm-dd hh:mm:ss:nnn).
  • But while inserting values, we are using the SYSDATETIME() function which returns the current date-time value in Datetime2 format. The SYSDATETIME() will return the date-time value with a fractional seconds precision of 7 (yyyy-mm-dd hh:mm:ss:nnnnnnn).
  • But still, the value got successfully inserted in the Datetime column, but it has ignored the last 4 characters.

String or binary data would be truncated datetime

Inserted Value

Read: Types of Backup in SQL Server

String or binary data would be truncated in SQL Server Stored Procedure

This error can also occur while executing a stored procedure in SQL Server, which is trying to insert new values in a column. But still, the reason behind this error will remain the same i.e, the column length is less than the value length that we are trying to insert.

Let’s understand this with the help of an example. And for this, we are using the following query to create a sample table.

--Creating table
CREATE TABLE Sample (
	id INT,
	Name VARCHAR(5),
	Joining_date DATETIME
);

Now take a look at the Name column, for the Name column we have defined the character length to be 5.

Next, we are using the following stored procedure to insert new records in the sample table.

ALTER PROCEDURE Insert_data
AS
--inserting values
insert into Sample (id, Name, Joining_date) values (1, 'Modesty Malley', GETDATE());

GO

Exec Insert_data

But while inserting the record through the stored procedure, we have specified the name value to be 14 characters. So, if we try to execute this procedure, we will get the following error.

String or binary data would be truncated stored procedure

Error while executing stored procedure

And the simplest solution to resolve this error is by modifying the column and increasing the column length. This solution is already been discussed in the topic above.

You may like the following SQL server tutorials:

  • SQL Server Row_Number
  • SQL Server Add Column + Examples
  • IDENTITY_INSERT in SQL Server
  • SQL Server stored procedure output parameter

So in this SQL Server tutorial, we have learned how to solve the “String or binary data would be truncated” error in a SQL Server, and we have also covered the below topics.

  • String or binary data would be truncated SQL Server Error
  • String or binary data would be truncated SQL Server Which Column
  • How to fix “String or binary data would be truncated”
  • String or binary data would be truncated SQL Server 2019
  • String or binary data would be truncated Datetime SQL Server
  • String or binary data would be truncated in SQL Server Stored Procedure

I am Bijay having more than 15 years of experience in the Software Industry. During this time, I have worked on MariaDB and used it in a lot of projects. Most of our readers are from the United States, Canada, United Kingdom, Australia, New Zealand, etc.

Want to learn MariaDB? Check out all the articles and tutorials that I wrote on MariaDB. Also, I am a Microsoft MVP.

To fix this error, patch to SQL Server 2016 SP2, CU6 or newer (including SQL Server 2017), and then turn on trace flag 460. You can enable it at the query level or at the server level.

First, let’s see the error happen: let’s create a table with small fields, and then try to insert more data than it holds.

CREATE TABLE dbo.CoolPeople(PersonName VARCHAR(20), PrimaryCar VARCHAR(20));

GO

INSERT INTO dbo.CoolPeople(PersonName, PrimaryCar)

VALUES (‘Baby’, ‘2006 Subaru Impreza WRX GD’);

GO

Baby’s car is longer than 20 characters, so when the insert statement runs, we get an error:

Msg 8152, Level 16, State 30, Line 5

String or binary data would be truncated.

The statement has been terminated.

String or binary data would be truncated

That sucks because we have no idea which field is causing the problem! It’s especially terrible when you’re trying to insert lots of rows.

If you’re on SQL Server 2019+,
here’s how to fix it.

Run this in the database where you want specific truncation warnings, and it takes effect right away:

ALTER DATABASE SCOPED CONFIGURATION

  SET VERBOSE_TRUNCATION_WARNINGS = ON;

Another way you could fix it is to upgrade your database’s compatibility level to 2019+ (150+), but that causes a whole bunch of other things to take effect too, like adaptive memory grants, and it’s going to require a whole lot more testing with your code. Just keep it simple for now and run the above if all you’re trying to do is know which column & row is being truncated.

If you’re on SQL Server 2016-2017:
to fix it, turn on trace flag 460.

Trace flag 460 was introduced in SQL Server 2016 Service Pack 2, Cumulative Update 6, and in SQL Server 2017. (You can find & download the most recent updates at SQLServerUpdates.com.) You can turn it on at the query level, like this:

INSERT INTO dbo.CoolPeople(PersonName, PrimaryCar)

VALUES (‘Baby’, ‘2006 Subaru Impreza WRX GD’)

OPTION (QUERYTRACEON 460);

GO

And now when the query runs, it shows you which column is getting clipped, and which row, too. In our case, we’ve only got one row – but in your real-life data, you’ll be much happier knowing which row’s triggering the error:

Msg 2628, Level 16, State 1, Line 9

String or binary data would be truncated in

table ‘StackOverflow2013.dbo.CoolPeople’, column ‘PrimaryCar’.

Truncated value: ‘2006 Subaru Impreza ‘.

You can turn on this trace flag at the query level as shown above, or at the server level:

That turns it on for everybody, not just you – so get everybody on your team to agree before you turn it on. This changes the error message number from 8152 to 2628 (as shown above), which means if you’ve built error handling based on the error number, you’re suddenly going to start getting different behavior.

I’m a fan of turning this trace flag on while I’m doing troubleshooting, and then once I’ve found the culprit, turning it back off again:

DBCC TRACEOFF(460, 1);

GO

In our case, once we’ve identified that Baby’s car is too large, we either need to change his car, or change the datatype in our table to make it bigger, or cast the data on the way in to explicitly strip the extra length off his car. A data chop shop, if you will.

Don’t leave this trace flag enabled.

There’s at least one bug with it as of today on SQL Server 2017 CU13: table variables will throw errors saying their contents are being truncated even when no data is going into them. Andrew Pruski reports:

Here’s that error that we were seeing @arrowdrive

Should be fixed now but one to watch out for. https://t.co/WbPrI1YHHJ

— Andrew Pruski ??????? (@dbafromthecold) March 20, 2019

Sadly, that behavior is NOT fixed, and here’s the simplest repro script I could build:

CREATE OR ALTER PROC dbo.Repro @BigString VARCHAR(8000) AS

BEGIN

DECLARE @Table TABLE ( SmallString VARCHAR(128) )

IF ( 1 = 0 )

/* This will never run */

INSERT INTO @Table ( SmallString )

VALUES(@BigString)

OPTION (QUERYTRACEON 460)

END

GO

DECLARE @BigString VARCHAR(8000) = REPLICATE(‘blah’,100)

EXEC dbo.Repro @BigString

GO

SQL Server 2017 CU13 still reports that the string will be truncated even though the insert doesn’t run:

Switch out the table variable for a temp table, and it works fine, as expected:

If you want to follow progress on that bug getting fixed, it’s here. Such a great example of why I’m not a fan of using trace flags by default – sure, they can fix issues, but they can also introduce unpredicted, unwanted behaviors. (And, uh, not a fan of table variables either.)

Update 2019/03/25 – the above bug is fixed in 2017 Cumulative Update 14. Yay!

  • Remove From My Forums
  • Question

  • I have a strange issue here.

    I have pinpointed which column is causing the error 

    Table A has many columns of which one of it is a varchar (50) column.

    When I try to insert data into this column it fails with Data Truncation error.

    I have validated the length and datalength of the data that will be stored in the column

    The size doesn’t exceed 35 for any of the values in the table.

    My source table has data with more than 50 characters but due to the where conditions in the query these get eliminated.

    So why do I get a Data Truncation error?

    Any help will be appreciated.

    Thanks

    Brunda

Answers

  • So why do I get a Data Truncation error?

    Hello Brunda,

    When you get that error, then you are really trying to insert longer string then defined for the column. Just as a test:

    CREATE TABLE #test(myField varchar(50));
    GO
    
    -- Works
    INSERT INTO #test
    VALUES (REPLICATE('A', 50));
    GO
    
    -- Raise error ".. would be truncated
    INSERT INTO #test
    VALUES (REPLICATE('A', 51));
    GO
    
    GO
    DROP TABLE #test;

    Check your source data and may data modifications in your query if it exceed the size.


    Olaf Helper

    Blog
    Xing

    • Proposed as answer by

      Monday, October 8, 2012 1:34 AM

    • Marked as answer by
      Iric Wen
      Wednesday, October 10, 2012 2:15 AM

First published on MSDN on Oct 24, 2018
In the recent announcement at Ignite 2018 on the release of SQL Server 2019 CTP 2.0, the new Big Data Clusters , data virtualization, support for UTF-8 , and Intelligent Query Processing were highlights. But we have also previewed work being done to address the infamous error message “String or binary data would be truncated”.

This error condition may happen for example when you implement an ETL between a source and a destination that does not have matching data types and/or length. In this context, the message «String or binary data would be truncated» is one of the most time-consuming troubleshooting processes to engage in, especially in large datasets. You probably know about and voted for this feedback item before.

Let’s see an example of what happens when you insert data into a column whose size is not big enough to store it:

USE [AdventureWorks2016CTP3]
GO
DROP TABLE IF EXISTS [Sales].[SalesOrderHeaderTest]
GO
CREATE TABLE [Sales].[SalesOrderHeaderTest](
[SalesOrderID] [INT] NOT NULL,
[CustomerID] [INT] NOT NULL,
[CreditCardApprovalCode] [nvarchar](13) NULL
)
GO

INSERT INTO [Sales].[SalesOrderHeaderTest]
SELECT [SalesOrderID], [CustomerID], [CreditCardApprovalCode]
FROM [Sales].[SalesOrderHeader]
GO

You receive following error message, which admittedly is not very helpful:

Msg 8152, Level 16, State 30, Line 13
String or binary data would be truncated.
The statement has been terminated.

We heard that. Which is why SQL Server 2019 introduces a new message , with additional context information. For the same operation, the new error message outputs the following:

Msg 2628, Level 16, State 1, Line 14
String or binary data would be truncated in table ‘AdventureWorks2016CTP3.Sales.SalesOrderHeaderTest’, column ‘CreditCardApprovalCode’. Truncated value: ‘1231736Vi8604’.
The statement has been terminated.

Ok, the new error message provides more context, and now I have the resulting truncated value (not the source value). This is simplifying the troubleshooting process, because now I know the truncated value starts with ‘1231736Vi8604′ – that’s 13 characters. And so I can go back to my data source, and locate the source record and its length:

SELECT [SalesOrderID], [CustomerID], [CreditCardApprovalCode], LEN([CreditCardApprovalCode])
FROM [Sales].[SalesOrderHeader]
WHERE CreditCardApprovalCode LIKE ‘1231736Vi8604%’

It’s 14 characters, and in my table definition I have a NVARCHAR(13). Well, I know what I need to do: change my table data type length.

This new message is also backported to SQL Server 2017 CU12 and in SQL Server 2016 SP2 CU6, but not by default. You need to enable trace flag 460 to replace message ID 8152 with 2628, either at the session or server level.

Note that for now, even in SQL Server 2019 CTP 2.0 the same trace flag 460 needs to be enabled. In a future SQL Server 2019 release, message 2628 will replace message 8152 by default.

EDIT (3/29/2019): For SQL Server 2019 CTP 2.4, Message 2628 becomes default under Database Compatibility Level 150. You can use the Database Scoped Configuration VERBOSE_TRUNCATION_WARNINGS to revert to back to Message 8152 as default. You can also use a lower Database Compatibility Level to revert back to Message 8152 as default.

Is there a limit to how much of my truncated string this error can return?
Let’s run a small test inserting a 123 character string into a VARCHAR(120):

CREATE TABLE myTable (myString VARCHAR(120));
GO
INSERT INTO myTable
VALUES (‘Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.’)
GO

Although my string gets truncated at 120 characters, the offending value that is shown is truncated to the first 100 characters:

Msg 2628, Level 16, State 1, Line 30
String or binary data would be truncated in table ‘AdventureWorks2016CTP3.dbo.myTable’, column ‘myString’. Truncated value: ‘Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore ‘.

Still plenty to find offending values in most data sources.

Pedro Lopes ( @SQLPedro ) – Senior Program Manager

Reading Time: 8 minutes

Speak guys!
In this article, I want to explain to you exactly what the message “String or binary data would be truncated” means, how can we identify which string is causing the error, how to hide this error message (if you want), what the change in sys.messages impacted this theme from SQL Server 2016+ and more!

So if you have trouble identifying and correcting occurrences of this error message, today will be the last time this will still be a problem for you.

One of the most common SQL Server errors, the message “String or binary data would be truncated” occurs when a value is trying to be inserted or updated in a table and it is larger than the maximum field size.

Example 1 — Maximum field size with 10 characters, string with 10:

Example 2 — Maximum field size with 10 characters, string with 11:

Example 3 — Difficult to identify the error

Look at the example 3. I am no longer entering a fixed value but from another table. This kind of situation may seem simple in a scenario such as the 1 and 2 examples, but when you are entering multiple records, especially taking data from multiple columns, it is difficult to identify which record and which column is causing this error message and This task may end up spending more time than you would like.

How to Bypass String Truncation

If you want to bypass string truncation at a given time or operation, you have the option to do so in SQL Server, as already shown in the article SQL Server — Why Not Use SET ANSI_WARNINGS OFF. I do not recommend using this technique at all, as it is a solution that is only masking the problem and not correcting it, but I would like to show that it exists and that it can be done.

When you use the SET ANSI_WARNINGS OFF command, you cause the SQL Server engine to no longer generate this error on execution, causing your 14 character text to be truncated and stored in the 10 character column. Excess characters will be silently discarded, ignoring and masking a problem writing your system data without anyone knowing.

Example:

SET NOCOUNT ON

SET ANSI_WARNINGS OFF

IF ((@@OPTIONS & 8) > 0) PRINT ‘SET ANSI_WARNINGS is ON’

IF (OBJECT_ID(‘tempdb..#Teste’) IS NOT NULL) DROP TABLE #Teste

CREATE TABLE #Teste ( Nome VARCHAR(10) )

INSERT INTO #Teste

VALUES (‘Dirceu Resende’) — 14 caracteres

SELECT * FROM #Teste

Return with SET ANSI_WARNINGS ON (Default):

Return with SET ANSI_WARNINGS OFF:

String or binary data would be truncated in SQL Server 2019

SQL Server 2019 was released on 04 November 2019, during Microsoft Ignite, and with it, a huge range of new features were officially released.

One of these new features is the new posts available on sys.messages, which I had already shared with you in my article. SQL Server 2019 — News and Features List since late August of 2018:

With this change, it’s now much easier to identify exactly where the truncation of values ​​is taking place:

According to traceflags documentation, the 460 traceflag replaces the data truncation 8152 ID message with the 2628 ID message. At the 150 database compatibility level onwards (2019), the 2628 ID message is the default and the 460 traceflag has no effect.

That is, this new behavior will only work automatically in SQL Server 2019 if the connection database is in 150 compatibility mode onwards.

Observation: This change to SQL Server 2019 sys.messages began in the CTP2.0 release and until the final release came out, it was not automatically activated, requiring the same changes as the 2017 and 2016 versions to work.

What has changed from SQL Server 2016 +

With the changes required for this implementation in SQL Server 2019, Microsoft eventually released this new message also in the 2016 (from SP2 Cumulative Update 6) and 2017 (From Cumulative Update 12) versions. And to be able to use this new message, we can use 2 in different ways:

1 Form: Using Initialization Parameter -T460

The first and most practical way is to enable 460 traceflag on the entire instance using the -T460 initialization parameter in the SQL Server service:

Once added, it will be necessary to restart the service and from then on, the new message will be working by default, without having to make any query changes:

2 Form: Using 460 Traceflag

One way that does not require restarting the SQL Server service and also does not require changing code is by using the DBCC TRACEON command, which allows you to enable this session level and instance level (global) traceflag:

Session level (only affects your session):

Instance level (global — affects all sessions):

Script used:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

PRINT @@VERSION

CREATE TABLE dbo.Teste (

    nome1 VARCHAR(10),

    nome2 VARCHAR(10),

    nome3 VARCHAR(10)

)

— Modo padrão — Mensagem anterior

INSERT INTO dbo.Teste (nome1, nome2, nome3)

VALUES(‘123456789’, ‘1234567890’, ‘12345678901’)

— Nível de instância (global — afeta todas as sessões)

DBCC TRACEON(460, 1);

GO

— Nível de sessão (afeta apenas a sua sessão)

DBCC TRACEON(460);

GO

— Após ativar a traceflag, a mensagem é alterada

INSERT INTO dbo.Teste (nome1, nome2, nome3)

VALUES(‘123456789’, ‘1234567890’, ‘12345678901’)

Remarks: To disable traceflag, use the DBCC TRACEOFF (460) or DBCC TRACEOFF (460, -1) command, depending on the parameter used for activation. If you have enabled instance-level traceflag, affecting all sessions, when you restart the SQL Server service, you must enable traceflag again.

There was a bug in SQL Server 2017 CU12 and CU13, which caused this “String or binary data would be truncated” error in insertion operations involving table variables, when the string size was larger than the field even in cases where the code was not executed (Ex: Within an IF with condition 1 = 0). This was fixed in SQL Server 2017 CU14.

Identifying String Truncation Before SQL Server 2016

If you are using a version prior to 2016 and have this difficulty in identifying which values ​​are breaking the limit of any column, I will share a simple script, which can identify this type of error even in the old versions of SQL Server, creating a table “clone” of the original, with the size of the columns set to the maximum, inserting the data in this new table and comparing the size used by the size of the columns in the original table.

Example situation where script can be used:

I tried to execute my INSERT command and it gave an error in some value, in some column, which I don’t know what it is. Now is the time when you think about the work you will have to do to identify this, especially if you have about 100 columns instead of just those 3 in the example .. Having to insert the data in a “clone” table and keep consulting and comparing the largest size of each column… It seems laborious ..

To make this column identification work easier, I will share with you the script below, which makes this identification for you. Remember to change the source table and script name from INSERT / UPDATE to the cloned table with your original script.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

DECLARE @Nome_Tabela VARCHAR(255) = ‘Teste’

— Crio uma tabela com a mesma estrutura

IF (OBJECT_ID(‘tempdb..#Tabela_Clonada’) IS NOT NULL) DROP TABLE #Tabela_Clonada

SELECT *

INTO

    #Tabela_Clonada

FROM

    dbo.Teste — Tabela original (LEMBRE-SE DE ALTERAR AQUI TAMBÉM)

WHERE

    1=2 — Não quero copiar os dados

— Agora, vou alterar todas as colunas varchar/char/nvarchar/nchar para varchar(max)

DECLARE @Query VARCHAR(MAX) = »

SELECT

    @Query += ‘ALTER TABLE #Tabela_Clonada ALTER COLUMN [‘ + B.[name] + ‘] ‘ + UPPER(C.[name]) + ‘(MAX); ‘

FROM

    sys.tables A

    JOIN sys.columns B ON B.[object_id] = A.[object_id]

    JOIN sys.types C ON B.system_type_id = C.system_type_id

WHERE

    A.[name] = @Nome_Tabela

    AND B.system_type_id IN (167, 175, 231, 239) — varchar/char/nvarchar/nchar

    AND B.max_length > 0

EXEC(@Query)

——————————————————————————————————————

— Faço a inserção dos dados que estão apresentando erro na tabela temporária (LEMBRE-SE DE ALTERAR AQUI TAMBÉM)

——————————————————————————————————————

INSERT INTO #Tabela_Clonada

— Alterar esse SELECT aqui pelo seu

SELECT [name], [type_desc] + ‘ | ‘ + lock_escalation_desc, SCHEMA_NAME([schema_id])

FROM sys.tables

— Crio uma tabela temporária com o tamanho máximo de caracteres de cada coluna

SET @Query = »

SELECT

    @Query = @Query + ‘SELECT ‘ + QUOTENAME(A.[name], »») + ‘ AS coluna, ‘ + QUOTENAME(B.[name], »») + ‘ AS tipo, MAX(DATALENGTH(‘ + QUOTENAME(A.[name]) + ‘)) AS tamanho FROM #Tabela_Clonada UNION ‘

FROM

    tempdb.sys.columns A

    JOIN sys.types B on B.system_type_id = A.system_type_id and B.[name] <> ‘sysname’

WHERE

    A.[object_id] = OBJECT_ID(‘tempdb..#Tabela_Clonada’)

    AND B.system_type_id IN (167, 175, 231, 239) — varchar/char/nvarchar/nchar

SET @Query = LEFT(@Query, LEN(@Query)6)

IF (OBJECT_ID(‘tempdb..#Tamanho_Maximo_Coluna’) IS NOT NULL) DROP TABLE #Tamanho_Maximo_Coluna

CREATE TABLE #Tamanho_Maximo_Coluna (

    coluna VARCHAR(255),

    tipo VARCHAR(255),

    tamanho INT

)

INSERT INTO #Tamanho_Maximo_Coluna

EXEC(@Query)

— E por fim, faço a comparação dos dados de uma tabela pela outra

SELECT

    B.[name] AS coluna,

    C.[name] AS tipo,

    B.max_length AS tamanho_atual,

    D.tamanho AS tamanho_necessario

FROM

    sys.tables A

    JOIN sys.columns B ON B.[object_id] = A.[object_id]

    JOIN sys.types C ON B.system_type_id = C.system_type_id

    JOIN #Tamanho_Maximo_Coluna D ON B.[name] = D.coluna

WHERE

    A.[name] = @Nome_Tabela

    AND B.system_type_id IN (167, 175, 231, 239) — varchar/char/nvarchar/nchar

    AND B.max_length < D.tamanho

Running this script will give you the exact return of which columns are too small for the data they are receiving and what is the optimal size to be able to store this data.

Observation: Be careful when using this script on very large tables. Because it needs to get the largest size of each column in the table, this operation can be a little slow and cumbersome on tables with millions of records. So have very careful!

I hope you enjoyed this article, a big hug and until the next post!
Hugs

References:

  • SQL Server 2019 — News and Features List
  • SQL Server — Why Not Use SET ANSI_WARNINGS OFF
  • How was SQL Server 2019 What’s New Live on the dotNET Channel?
  • https://www.sqlshack.com/sql-truncate-enhancement-silent-data-truncation-in-sql-server-2019/
  • https://imasters.com.br/banco-de-dados/adeus-string-binary-data-truncated
  • https://www.brentozar.com/archive/2019/03/how-to-fix-the-error-string-or-binary-data-would-be-truncated/

You might have get the data truncation error in SQL Server such as “String or binary data would be truncated” . It does not specify the exact source of error in terms of database name, table name, column name and truncated values.

It usually happens when a data value somewhere does not fit under a table’s column data type size so it returns only “String or binary data would be truncated”  error rather than giving a detailed error .

Sometimes it becomes worse when you are performing bulk insertions and data having have too many columns so in this situation it becomes hard to find out which column and data causing the issue.

In SQL Server 2019, you can see detailed error of truncation like database name, table name and column name that causing issue.

Lets demonstrate a truncation error for SQL Server different different versions until SQL Server 2017 and SQL server 2019.

Check SQL Server Verbose Truncation Warnings until SQL Server 2017

Here we are using SQL Server 2017 and its compatibility level is 140.

To check database compatibility level > Right Click on database > then Click on Properties > click on Option

You can also check same using T-SQL query.

select name , Compatibility_Level, collation_name from sys.databaseswhere name = 'SQLServerTutorials'

Now create a table named as TBLX, here for column ‘NAME’  data type size is given 5.

Lets try to insert value for ‘NAME’ column of size more than 5 to explore the truncation error .

CREATE TABLE TBLX
(
ID INT identity(1,1),
NAME VARCHAR(5),
)
GO

INSERT INTO TBLX VALUES ('SQL SERVER')

As you can see, It gives an error saying –‘String or binary data would be truncated.’

It does not provide exact error message so it makes hard to find out the root cause of error when performing bulk insertions or dealing with large set of queries, multiple columns so on..

Now you take the same queries and execute in SQL Server 2019, to see whether it gives detailed error or not.

Check SQL Server Verbose Truncation Warnings with SQL Server 2019

It requires SQL Server Compatibility level to 150.

If database compatibility level is other than 150, it can be changed using below T-SQL Query.

ALTER DATABASE database_name SET COMPATIBILITY_LEVEL = 150.

Lets execute the same Queries again in SQL server 2019

CREATE TABLE TBLX
(
ID INT identity(1,1),
NAME VARCHAR(5),
)
GO

INSERT INTO TBLX VALUES (‘SQL SERVER’)

Here you can see, It gives a detailed error of truncation string in terms of database name, table name , column name and truncated value.

Also Read..

 4,829 total views,  1 views today

CREATE TABLE dbo.CoolPeople(PersonName VARCHAR(20), PrimaryCar VARCHAR(20));
GO
INSERT INTO dbo.CoolPeople(PersonName, PrimaryCar)
VALUES ('Baby', '2006 Subaru Impreza WRX GD');
GO

Машина Baby длиннее, чем 20 символов, поэтому при выполнении оператора INSERT получаем ошибку:

Msg 8152, Level 16, State 30, Line 5
String or binary data would be truncated.
The statement has been terminated.

Это засада, поскольку у нас нет идей относительно того, какое поле вызвало проблемы! Это особенно ужасно, когда вы пытаетесь вставить множество строк.

Чтобы пофиксить ошибку, включите флаг трассировки 460

Флаг трассировки 460 был введен в SQL Server Sevice Pack 2, Cummulative Update 6, и в SQL Server 2017. (Вы можете найти и загрузить последние обновления с SQLServerUpdates.com.) Вы можете включить флаг на уровне запроса, например:

INSERT INTO dbo.CoolPeople(PersonName, PrimaryCar)
VALUES ('Baby', '2006 Subaru Impreza WRX GD')
OPTION (QUERYTRACEON 460);
GO

Теперь, если выполнить запрос, он покажет вам, какой столбец усекается, а также какая строка. В нашем случае мы имеем только одну строку, но в реальной жизни много полезней будет знать, какая строка вызвала ошибку:

Msg 2628, Level 16, State 1, Line 9
String or binary data would be truncated in
table 'StackOverflow2013.dbo.CoolPeople', column 'PrimaryCar'.
Truncated value: '2006 Subaru Impreza '.

Вы можете включить этот флаг трассировки как на уровне запроса (в нашем примере выше), так и на уровне сервера:

DBCC TRACEON(460, -1);
GO

Этот оператор включает его для всех, а не только для вас — поэтому сначала договоритесь со своей командой разработчиков, прежде чем включать его. Это изменит номер ошибки 8152 на 2628 (как показано выше), означающее, что если вы строили обработку ошибок на основании этих номеров, вы сразу получите другое поведение.

Я любитель включения этого флага трассировки на время отладки и изучения, но как только обнаруживаю источник проблем, выключаю его, снова выполнив команду:

DBCC TRACEON(460, -1);
GO

В нашем случае, как только мы идентифицировали избыточную длину машины Baby, необходимо либо изменить название машины, либо изменить тип данных в нашей таблице, чтобы сделать размер столбца больше. Можно также предварительно обрабатывать данные, явно отсекая избыточные символы. Мастерская по разборке данных, если хотите.

Не оставляйте этот флаг включенным

По крайней мере, имеется связанный с этим один баг в SQL Server 2017 CU13: табличные переменные будут выбрасывать ошибки, говорящие, что их содержимое усекается, даже если никакие данные не вставляются в них.

Вот простой скрипт, чтобы проверить, пофиксили ли это поведение:

CREATE OR ALTER PROC dbo.Repro @BigString VARCHAR(8000) AS
BEGIN
DECLARE @Table TABLE ( SmallString VARCHAR(128) )
IF ( 1 = 0 )
/* Это никогда не выполняется */
INSERT INTO @Table ( SmallString )
VALUES(@BigString)
OPTION (QUERYTRACEON 460)
END
GO
DECLARE @BigString VARCHAR(8000) = REPLICATE('blah',100)
EXEC dbo.Repro @BigString
GO

SQL Server 2017 CU13 всё еще сообщает об усечении строки, даже если строка не вставляется:

Переключение с табличной переменной на временную таблицу приводит к ожидаемому поведению:

Это замечательный пример, почему не следует использовать флаги трассировки по умолчанию. Конечно, они могут пофиксить проблемы, но они также могу вызвать непредсказуемое или нежелательное поведение. (И, вообще, я не фанат табличных переменных.)


Asked by: Destinee Wuckert

Score: 5/5
(35 votes)

Solution to fix String or binary data truncation

  1. Fix the data that we are trying to insert or update. Data length should not exceed the maximum allowed limit for the particular column.
  2. Use ‘SET ANSI_WARNINGS OFF’ to truncate the data and insert it as per column maximum string length.

What does data truncated mean in SQL?

TRUNCATE TABLE removes all rows from a table, but the table structure and its columns, constraints, indexes, and so on remain. … To remove the table definition in addition to its data, use the DROP TABLE statement.

What does data truncation error mean?

So it means the new incident subjects cannot fit into your varchar(80) in the mirror database. To fix this, either manually alter the mirror table (column) or re-create the whole synchronization and perform an initial data load.

How do I ignore data truncation error in SSIS?

In SSIS, how to ignore Truncation errors in XML source?

  1. double-click on the XML source.
  2. go to the Error output tab.
  3. select a column.
  4. select «Ignore Failure» in the drop-down list that corresponds to the «Truncation».
  5. Click OK.

How do you fix error string or binary data would be truncated?

To fix this error, patch to SQL Server 2016 SP2, CU6 or newer (including SQL Server 2017), and then turn on trace flag 460. You can enable it at the query level or at the server level. First, let’s see the error happen: let’s create a table with small fields, and then try to insert more data than it holds.

34 related questions found

What is truncation error in SQL Server?

We normally call it as silent truncation and occur when we try to insert string data (varchar, nvarchar, char, nchar) into more than the size of the column. If we are dealing with the huge amount of data with lots of columns, if we get any error it becomes difficult to find out which column, data caused the issue.

How do you truncate a string in SQL?

The basic syntax is SUBSTR(string, position, length), where position and length are numbers. For example, start at position 1 in the string countryName, and select 15 characters. Length is optional in MySQL and Oracle, but required in SQL Server.

How do I fix a truncation error in Excel?

So if your package is failing due to a truncation error on a string column, simple way is to add a dummy row as first row in the Excel file with data greater than 255 characters in the column that is causing truncation error.

What is truncation of data?

From Wikipedia, the free encyclopedia. In databases and computer networking data truncation occurs when data or a data stream (such as a file) is stored in a location too short to hold its entire length.

How do I truncate a column in SQL Server?

ALTER TABLE tableName DROP COLUMN columnName ; ALTER TABLE tableName DROP COLUMN columnName ; Example 1: Let us DROP the gender column from our DataFlair_info database. We can see the gender column is no longer available in our database.

What is a truncation error example?

In computing applications, truncation error is the discrepancy that arises from executing a finite number of steps to approximate an infinite process. For example, the infinite series 1/2 + 1/4 + 1/8 + 1/16 + 1/32 … adds up to exactly 1.

How do you reduce discretization error?

Discretization error can usually be reduced by using a more finely spaced lattice, with an increased computational cost.

What is true error?

In general, the true error is the difference between the true value of a quantity and the observed measurement (Muth, 2006). … True error is also sometimes defined as the difference between the true value found by a calculation, and the approximate value found by using a numerical method.

What is difference between truncate and delete command?

Key differences between DELETE and TRUNCATE

The DELETE statement is used when we want to remove some or all of the records from the table, while the TRUNCATE statement will delete entire rows from a table. DELETE is a DML command as it only modifies the table data, whereas the TRUNCATE is a DDL command.

How do you write a delete query?

To create a delete query, click the Create tab, in the Queries group, click Query Design. Double-click each table from which you want to delete records, and then click Close. The table appears as a window in the upper section of the query design grid.

What is truncate command?

SQL Truncate is a data definition language (DDL) command. It removes all rows in a table. SQL Server stores data of a table in the pages. The truncate command deletes rows by deallocating the pages. … At a high level, you can consider truncate command similar to a Delete command without a Where clause.

What is an example of truncation?

Truncation is a searching technique used in databases in which a word ending is replaced by a symbol. … For example: If the truncation symbol is *, then the truncated word, laugh*, will search for results containing laugh, laughter, laughing etc. Note: Placing the truncation symbol too soon in a word should be avoided.

What is truncation effect?

From Wikipedia, the free encyclopedia. In statistics, truncation results in values that are limited above or below, resulting in a truncated sample. A random variable is said to be truncated from below if, for some threshold value , the exact value of is known for all cases , but unknown for all cases .

How do you know if data is censored?

So to summarize, data are censored when we have partial information about the value of a variable—we know it is beyond some boundary, but not how far above or below it. In contrast, data are truncated when the data set does not include observations in the analysis that are beyond a boundary value.

How do I push Excel data into SQL Server?

Our Simple Example

  1. Step 1 – Create a Project. …
  2. Step 2 – Create a Connection to your SQL Server Database. …
  3. Step 3 – Create a Table. …
  4. Step 4 – Create an Excel Connection. …
  5. Step 5 – Create a Data Flow Task. …
  6. Step 6 – Creating the Excel Source. …
  7. Step 7 – Removing Rubbish Data. …
  8. Step 8 – Piping the ‘OK Data’ into a SQL Server Table.

What is import and export data in SQL Server?

The Import and Export wizard in SQL Server Management Studio (SSMS) assists users with copying data from one location to another. The export tasks lets you export data into another database, Excel, text files, etc. and the import tasks let you load data from other databases or sources like Excel, text files, etc.

How do you handle errors in SSIS?

Create SSIS package for error handling

  1. Create SSIS package for error handling. …
  2. Right-click on [Learn Error Handling] task and edit. …
  3. You can notice the three things in the below image: …
  4. Click on a column to verify the data in the source text file and available columns.

How do I get last three characters of a string in SQL?

SQL Server RIGHT() Function

  1. Extract 3 characters from a string (starting from right): SELECT RIGHT(‘SQL Tutorial’, 3) AS ExtractString;
  2. Extract 5 characters from the text in the «CustomerName» column (starting from right): …
  3. Extract 100 characters from a string (starting from right):

How do I get the last character of a string in SQL?

To get the first n characters of string with MySQL, use LEFT(). To get the last n char of string, the RIGHT() method is used in MySQL.

What is the meaning of like 0 0?

Feature ends with two 0’s. Feature has more than two 0’s. Feature has two 0’s in it, at any position.

I’m working with a fairly simple database, from a Java application. We’re trying to insert about 200k of text at a time, using the standard JDBC mysql adapter. We intermittently get a com.mysql.jdbc.MysqlDataTruncation: Data truncation: Data too long for column error.

The column type is longtext, and database collation is UTF-8. The error shows up using both MyISAM and InnoDB table engines. Max packet size has been set ot 1 GB on both client and server sides, so that shouldn’t be causing a problem, either.

Kuro Neko's user avatar

asked Sep 16, 2008 at 14:44

Check that your UTF-8 data is all 3-byte Unicode. If you have 4-byte characters (legal in Unicode and Java, illegal in MySQL 5), it can throw this error when you try to insert them. This is an issue that should be fixed in MySQL 6.0.

answered Sep 16, 2008 at 15:11

Avi's user avatar

AviAvi

19.9k4 gold badges55 silver badges69 bronze badges

2

Well you can make it ignore the error by doing an INSERT IGNORE which will just truncate the data and insert it anyway. (from http://dev.mysql.com/doc/refman/5.0/en/insert.html )

If you use the IGNORE keyword, errors
that occur while executing the INSERT
statement are treated as warnings
instead. For example, without IGNORE,
a row that duplicates an existing
UNIQUE index or PRIMARY KEY value in
the table causes a duplicate-key error
and the statement is aborted. With
IGNORE, the row still is not inserted,
but no error is issued. Data
conversions that would trigger errors
abort the statement if IGNORE is not
specified. With IGNORE, invalid values
are adjusted to the closest values and
inserted; warnings are produced but
the statement does not abort.

answered Sep 16, 2008 at 14:52

Nicholas's user avatar

NicholasNicholas

5753 silver badges14 bronze badges

0

In mysql you can use MEDIUMTEXT or LONGTEXT field type for large text data

Satish Sharma's user avatar

answered Oct 16, 2012 at 12:02

grigson's user avatar

grigsongrigson

3,44829 silver badges20 bronze badges

It sounds to me like you are trying to put too many bytes into a column. I ran across a very similar error with MySQL last night due to a bug in my code. I meant to do

foo.status = 'inactive'

but had actually typed

foo.state = 'inactive'

Where foo.state is supposed to be a two character code for a US State ( varchar(2) ). I got the same error as you. You might go look for a similar situation in your code.

answered Sep 16, 2008 at 14:55

Aaron's user avatar

AaronAaron

2,4031 gold badge24 silver badges25 bronze badges

I just hit this problem and solved it by removing all the non-standard ascii characters in my text (following the UTF-8 advice above).

I had the problem on a Debian 4, Java 5 system; but the same code worked fine with Ubuntu 9.04, Java 6. Both run MySql 5.

answered Jul 10, 2009 at 16:06

Szemere's user avatar

SzemereSzemere

1881 silver badge5 bronze badges

  1. Situation restrictions

   error solution hereDiscuss only

     When using Mybatis, this kind of error occurs when an array is passed in and the <foreach> tag is used;

  2. Error case

   mapper.java

    /**
     * @Description: Cancel the factory inspection notice
     * SupplierCheckfactoryInformMapper
     * cancelNotifyToCheckFac
     * @param params
           * 2016-8-24 3:42:44 PM
     */
    public void cancelNotifyToCheckFac(
          @Param("regId")Integer regId,
          @Param("updateDt")Date updateDt,
          @Param("supplierIds")BigInteger[] supplierIds
         );

    mapper.xml

<update id="cancelNotifyToCheckFac">
    UPDATE
        t_supplier_regaccount_info tsri,
        t_supplier_checkfactory_inform tsci
    SET
        status = 2,
        update_dt = #{updateDt}
    WHERE
        tsri.supplier_id = tsci.supplier_id
        AND
        tsri.supplier_id in 
        <foreach collection="supplierIds" item="item" index="index" open="(" separator="," close=")">
            #{supplierIds}
        </foreach>
        AND
        tsri.reg_id = #{regId}
        AND
        tsci.status = 0
</update>

     error message:

### Error updating database.  Cause: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Truncated incorrect DOUBLE value: 'xACxEDx00x05urx00x17[Ljava.math.BigInteger;x0E|xDBFxE0:`xC6x02x00x00xpx00x00x00x01srx00x14java.math.BigIntege'
### The error may involve defaultParameterMap
### The error occurred while setting parameters
### SQL: UPDATE   t_supplier_regaccount_info tsri,   t_supplier_checkfactory_inform tsci  SET   status = 2,   update_dt = ?  WHERE   tsri.supplier_id = tsci.supplier_id   AND   tsri.supplier_id in     (          ?    )    AND   tsri.reg_id = ?   AND   tsci.status = 0
### Cause: com.mysql.jdbc.MysqlDataTruncation: Data truncation: Truncated incorrect DOUBLE value: 'xACxEDx00x05urx00x17[Ljava.math.BigInteger;x0E|xDBFxE0:`xC6x02x00x00xpx00x00x00x01srx00x14java.math.BigIntege'
; SQL []; Data truncation: Truncated incorrect DOUBLE value: 'xACxEDx00x05urx00x17[Ljava.math.BigInteger;x0E|xDBFxE0:`xC6x02x00x00xpx00x00x00x01srx00x14java.math.BigIntege'; nested exception is com.mysql.jdbc.MysqlDataTruncation: Data truncation: Truncated incorrect DOUBLE value: 'xACxEDx00x05urx00x17[Ljava.math.BigInteger;x0E|xDBFxE0:`xC6x02x00x00xpx00x00x00x01srx00x14java.math.BigIntege'
 ERROR 2016-09-18 15:03:17,661 util.web.ExceptionAdvisor: internal/external requestor: /admin
 ERROR 2016-09-18 15:03:17,661 util.web.ExceptionAdvisor: Request IP:0:0:0:0:0:0:0:1
 ERROR 2016-09-18 15:03:17,662 util.web.ExceptionAdvisor: Request parameter: {supplierId=26};
 ERROR 2016-09-18 15:03:17,662 util.web.ExceptionAdvisor: =====service notification ends, continue to throw up BusinessException=====
 WARN 2016-09-18 15:03:17,669  org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver: Handler execution resulted in exception
 common.model.BusinessException: Sorry, there is an internal error in the program and the operation failed! Please try again later or contact the administrator!

    3. Error analysis

    The error message here: Data truncation: Truncated incorrect DOUBLE value

      3.1: onlinemainwrong reasonYes: the and keyword appears in the set in the update statement, and a comma <,> should be used instead; the error is reported hereDoes not belongThis situation

      3.2:The reason for the error hereThe following is: The parameter name #{supplierIds} cannot be used in the <foreach> tag, but #{item} should be used, which seems to be a fixed wording; the root cause is not clear yet, wait for the guidance of the great god;

    4. After code modification

    mapper.xml

<update id="cancelNotifyToCheckFac">
    UPDATE
        t_supplier_regaccount_info tsri,
        t_supplier_checkfactory_inform tsci
    SET
        status = 2,
        update_dt = #{updateDt}
    WHERE
        tsri.supplier_id = tsci.supplier_id
        AND
        tsri.supplier_id in 
        <foreach collection="supplierIds" item="item" index="index" open="(" separator="," close=")">
                           #{item} <-- *This is the reason for the error* --> 
        </foreach>
        AND
        tsri.reg_id = #{regId}
        AND
        tsci.status = 0
</update>

  Other codes will not be modified;

    5. Results

After      is modified, the record can be updated normally, and no error will be reported;

  • Ошибка error this is not freearc archive or this archive is corrupt
  • Ошибка error sxs assembly missing
  • Ошибка error steam id bad length
  • Ошибка error spawn wine enoent
  • Ошибка error opening dir