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

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);

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..

The maximal length of the target column is shorter than the value you try to insert.
Rightclick the table in SQL manager and go to 'Design' to visualize your table structure and column definitions.
Edit:
Try to set a length on your nvarchar inserts thats the same or shorter than whats defined in your table.

In my case, I was getting this error because my table had
varchar(50)
but I was injecting 67 character long string, which resulted in thi error. Changing it to
varchar(255)
fixed the problem.

Specify a size for the item and warehouse like in the [dbo].[testing1] FUNCTION
#trackingItems1 TABLE (
item nvarchar(25) NULL, -- 25 OR equal size of your item column
warehouse nvarchar(25) NULL, -- same as above
price int NULL
)
Since in MSSQL only saying only nvarchar is equal to nvarchar(1) hence the values of the column from the stock table are truncated

SQL Server 2016 SP2 CU6 and SQL Server 2017 CU12
introduced trace flag 460 in order to return the details of truncation warnings.
You can enable it at the query level or at the server level.
Query level
INSERT INTO dbo.TEST (ColumnTest)
VALUES (‘Test truncation warnings’)
OPTION (QUERYTRACEON 460);
GO
Server Level
DBCC TRACEON(460, -1);
GO
From SQL Server 2019 you can enable it at database level:
ALTER DATABASE SCOPED CONFIGURATION
SET VERBOSE_TRUNCATION_WARNINGS = ON;
The old output message is:
Msg 8152, Level 16, State 30, Line 13
String or binary data would be truncated.
The statement has been terminated.
The new output message is:
Msg 2628, Level 16, State 1, Line 30
String or binary data would be truncated in table 'DbTest.dbo.TEST', column 'ColumnTest'. Truncated value: ‘Test truncation warnings‘'.
In a future SQL Server 2019 release, message 2628 will replace message 8152 by default.

Related

Why I'm getting arithmetic overflow error when inserting bigint number to a bigint column?

I'm trying to insert a number to a column. Column datatype is BIGINT and I'm pretty sure that my number doesn't exceed the max value of BIGINT but still I get
Msg 8115, Level 16, State 2, Line 40
Arithmetic overflow error converting expression to data type int.
The statement has been terminated.
My recent activity was I change the datatype of that column from INT to BIGINT. I think somewhere internally my column is still defined as INT.
Here is my script.
Insert into Customer(Cust_ID)
Select 2150000000
Column Cust_ID datatype is BIGINT in the designer. It is also the PRIMARY_KEY and many table reference it.
EDIT:
Here are some of the migration scripts
DROP TABLE dbo.Customer
GO
EXECUTE sp_rename N'dbo.Tmp_Customer', N'Customer', 'OBJECT'
GO
OK I already found the answer. My table has custom constraints which call scalar functions which requires an INT parameter.
Changing all those function's parameter to BIGINT solves the problem.

Conversion failed when converting the varchar value '0%' to data type int

I'm facing a problem with SQL Server.
I've created a table like this:
create table Components
(
pk BIGINT NOT NULL PRIMARY KEY IDENTITY,
id VARCHAR(50),
descr VARCHAR(50),
in_m INT,
in_iy INT,
p_fw VARCHAR(5000)
);
and I'm trying to insert a couple of values:
insert into Components (id, descr, in_m, in_iy, p_fw)
values ('FW000_A', '0%', 0, 0, '[0.0,0.0,0.0]'),
('FW000_B', '1%', 1, 1, '[1.0,1.0,1.0]');
I get the following error:
Msg 245, Level 16, State 1, Line 111
Conversion failed when converting the varchar value '0%' to data type int.
even though the column descr is correctly defined as varchar(50).
Can anybody help me please? Why is SQL Server trying to convert my strings to int values?
What's missing from your question is that you have more than just the two values lines you've shown, and one of the other ones has an integer literal for the descr column, rather than a string.
This example produces the same error:
declare #t table (Descr varchar(50) not null)
insert into #t(Descr) values
('0%'),
(12)
What I believe happens is that SQL Server first tries to determine the data types for all columns in the values clause. Using data type precedence rules, it observes a varchar literal in one row and an int literal in the other, and so determines that the overall type for this column is int and attempts to perform the conversion that leads to the error.
During this process, it does not use any information about the target table into which the values are going to be placed, including the data types of the columns there.
run this and verify the data types;
sp_columns Components
Looks like 'descr' is really an integer

Error in store procedure execution

When I am trying t execute a stored procedure, It is showing this error
Msg 8152, Level 16, State 14, Procedure MA01003_SUM1, Line 12
String or binary data would be truncated.
The statement has been terminated.
Following is the stored procedure
ALTER procedure [dbo].[MA01003_SUM1]
as
Begin
declare #desc as varchar(50)
set #desc = dbo.sdescription(1,0,3)
declare #cost as float
set #cost = dbo.SCost(0)
Insert into SummaryLoad(
SL_TierName,
SL_CorporateName,
SL_HospiceName,
SL_GroupName,
SL_DateKey,
SL_FactAmt,
SL_AHT,
SL_headingNo,
SL_Staffno,
SL_factno,
SL_Description,
SL_Cost)
SELECT [MA_TierName]
,[MA_CorporateName]
,[MA_HospiceName]
,[MA_GroupName]
,[MA_Datekey]
,SUM([MA_NumContacts]) Contacts
,SUM([MA_Duration]) ActualHandleTime,
'1',
'0',
'3',
#desc,
#cost
FROM [DM_ResourceUtilization].[dbo].[MedicationsAdded]
GROUP BY [MA_TierName]
,[MA_CorporateName]
,[MA_HospiceName]
,[MA_GroupName]
,[MA_Datekey]
end
Probable are the chances that data type or width of table SummaryLoad is not matching with that of select statement output. Please see the following script to illustrate the concept -
use tempdb
go
create table #test ( c1 varchar(5))
go
declare #desc as varchar(10) -- Width is 10 only
set #desc = 'AAAAAABBBBBBBBBBBbbCCCCCCCCCCCCCCcDDDDDDDDDDDDDD' -- Assigning higher width value
select #desc -- No error thrown, SQL server do the data truncation silently
insert into #test(c1) values ( #desc ) -- Here SQL server throws an error,
-- reason - value in #desc is of width 10, but target column width is 5
Better you can find the offending column or statement by yourself without much difficulty. To do this comment out each column and its values from the procedure and then invoke it in a transaction OR give a constant value that would match with the target data type for each column one by one. Sample follows -
Insert into SummaryLoad(
SL_TierName,
SL_CorporateName,
SL_HospiceName,
SL_GroupName,
SL_DateKey,
SL_FactAmt,
SL_AHT,
SL_headingNo,
SL_Staffno,
SL_factno,
SL_Description,
SL_Cost)
SELECT
/*[MA_TierName] */ -- Commented out
'A' -- Sample value, alter the procedure with this insert and run in transaction
-- If that is successful, this is offending column. Change the value with matching
-- data type and width of column SL_TierName of table SummaryLoad
-- Repeat this for all columns till you find the offending column(s)
,[MA_CorporateName]
,[MA_HospiceName]
,[MA_GroupName]
,[MA_Datekey]
,SUM([MA_NumContacts]) Contacts
,SUM([MA_Duration]) ActualHandleTime,
'1',
'0',
'3',
#desc,
#cost
FROM [DM_ResourceUtilization].[dbo].[MedicationsAdded]
GROUP BY [MA_TierName]
,[MA_CorporateName]
,[MA_HospiceName]
,[MA_GroupName]
,[MA_Datekey]
Modified procedure should be called in a transaction to ensure that your data is not affected by this test. Procedure can be called in a transaction using following statement
begin transaction
exec [dbo].[MA01003_SUM1]
rollback transaction
As per your error message :
Msg 8152, Level 16, State 14, Procedure MA01003_SUM1, Line 12
String or binary data would be truncated.
The statement has been terminated.
It is possibly your column width issue which is overlapped or oveflow then the size defined in column.
So, you have to just check which column have how much size & what you passing the data (i.e. size of data) which greater then size defined in column.

SQL Server 2005 I am not able to read from a table

Please suppose that in SQL Server 2005, if you launch the following query:
SELECT CHICKEN_CODE FROM ALL_CHICKENS WHERE MY_PARAMETER = 'N123123123';
you obtain:
31
as result.
Now, I would like to write a function that, given a value for MY_PARAMETER, yields the corresponding value of CHICKEN_CODE, found in the table ALL_CHICKENS.
I have written the following stored function in SQL Server 2005:
ALTER FUNCTION [dbo].[determines_chicken_code]
(
#input_parameter VARCHAR
)
RETURNS varchar
AS
BEGIN
DECLARE #myresult varchar
SELECT #myresult = CHICKEN_CODE
FROM dbo.ALL_CHICKENS
WHERE MY_PARAMETER = #input_parameter
RETURN #myresult
END
But if I launch the following query:
SELECT DBO.determines_chicken_code('N123123123')
it yields:
NULL
Why?
Thank you in advance for your kind cooperation.
define the length of your varchar variables like this
varchar(100)
Without the 100 (or whatever length you choose) its lengh is 1 and the where clause will filter out the correct results.
Specify a length for your varchar (ex.: varchar(100)). Without length, varchar = 1 char.
As per other PS, You can store only one char in the #myresult because you have not specified any length, bcoz 1 char length is default for Varchar datatype.
Why we are getting NUll, not the first char:
If there are multiple records are filtered on basis of Where clause in ALL_CHICKENS table then the value of CHICKEN_CODE column is picked up from last row in ALL_CHICKENS table.
It seems that the last row has null value in CHICKEN_CODE column.
Specify a length for #input_parameter, #myresult as by default varchar lengh is 1.

String or binary data would be truncated

I am trying to execute the following SQL query using MS SQL Server Management Studio express.
Insert INTO SU_PRO_RE ( d_id, fis_year, last_dp, budget_amt) VALUES ( 'A','2011', 0, 205000.00);
Everything looks correct to me but every time i try to execute it it has the following:
String or binary data would be truncated.
The statement has been terminated.
(0 row(s) affected)
The tables as set as follows:
d_id = char(1) *PK*
fis_year = char(2) *PK*
last_dp = smallint
budget_amt = money
I'm not sure what i am doing incorrect but i'm sure i am just over looking something very obvious so any help would be great! :)
Thanks,
David
fis_year is defined as char(2) but you're trying to insert a 4 character value of '2011'.
Well, the field fis_year is defined as CHAR(2), and you are trying to insert a value that has 4 charachters long.