Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String or binary data would be truncated. The statement has been terminated

Tags:

sql

sql-server

I have met some problem with the SQL server, this is the function I created:

ALTER FUNCTION [dbo].[testing1](@price int) RETURNS @trackingItems1 TABLE (    item       nvarchar  NULL,    warehouse   nvarchar NULL,    price int   NULL )  AS BEGIN    INSERT INTO @trackingItems1(item, warehouse, price)    SELECT ta.item, ta.warehouse, ta.price     FROM   stock ta    WHERE  ta.price >= @price;      RETURN; END; 

When I write a query to use that function like the following it getting the error

String or binary data would be truncated. The statement has been terminated

How can I fix this problem?

select * from testing1(2) 

This is the way I create the table

CREATE TABLE stock(item       nvarchar(50) NULL,                    warehouse   nvarchar(50) NULL,                    price int NULL); 
like image 416
user2098512 Avatar asked Feb 22 '13 07:02

user2098512


People also ask

How do you fix String or binary data would be truncated The statement has been terminated?

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.

How do I fix String or binary data would be truncated in SQL?

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.

Why String or binary data would be truncated The statement has been terminated?

"String or binary data would be truncated." The "String or binary data would be truncated" error occurs when the value persisted in a field is higher (in character count) than the one the database column max value allows.


Video Answer


1 Answers

When you define varchar etc without a length, the default is 1.

When n is not specified in a data definition or variable declaration statement, the default length is 1. When n is not specified with the CAST function, the default length is 30.

So, if you expect 400 bytes in the @trackingItems1 column from stock, use nvarchar(400).

Otherwise, you are trying to fit >1 character into nvarchar(1) = fail

As a comment, this is bad use of table value function too because it is "multi statement". It can be written like this and it will run better

ALTER FUNCTION [dbo].[testing1](@price int) RETURNS AS    SELECT ta.item, ta.warehouse, ta.price     FROM   stock ta    WHERE  ta.price >= @price; 

Of course, you could just use a normal SELECT statement..

like image 175
gbn Avatar answered Sep 29 '22 13:09

gbn