SQL Server Error : String or binary data would be truncated - sql-server

My table :
log_id bigint
old_value xml
new_value xml
module varchar(50)
reference_id bigint
[transaction] varchar(100)
transaction_status varchar(10)
stack_trace ntext
modified_on datetime
modified_by bigint
Insert Query :
INSERT INTO [dbo].[audit_log]
([old_value],[new_value],[module],[reference_id],[transaction]
,[transaction_status],[stack_trace],[modified_on],[modified_by])
VALUES
('asdf','asdf','Subscriber',4,'_transaction',
'_transaction_status','_stack_trace',getdate(),555)
Error :
Msg 8152, Level 16, State 14, Line 1
String or binary data would be truncated.
The statement has been terminated.
Why is that ???

You're trying to write more data than a specific column can store. Check the sizes of the data you're trying to insert against the sizes of each of the fields.
In this case transaction_status is a varchar(10) and you're trying to store 19 characters to it.

this type of error generally occurs when you have to put characters or values more than that you have specified in Database table like in this case:
you specify
transaction_status varchar(10)
but you actually trying to store
_transaction_status
which contain 19 characters.
that's why you faced this type of error in this code..

This error is usually encountered when inserting a record in a table where one of the columns is a VARCHAR or CHAR data type and the length of the value being inserted is longer than the length of the column.
I am not satisfied how Microsoft decided to inform with this "dry" response message, without any point of where to look for the answer.

Related

DECRYPTBYPASSPHRASE sometimes returns NULL for the same input and passphrase

A strange issue that occurs sometimes.
The environment is Microsoft SQL Server Web (64-bit) on Windows Server 2016 Standard (10.0). SQL Server version is 14.0.1000.169
I have a table, TableA with a column ColEncrypted and primary key column PK. The data type of PK is int and it is auto incremented. The datatype of ColEncrypted is varbinary(500) and the column is nullable. This column is used to stored date value in encrypted format. Before encrypting the date, it is first converted to nvarchar in format yyyyMMdd. So for e.g. April 1, 2020 becomes '20200401'. Thus the data to be encrypted is always 8 characters in length. This value is then encrypted using the T-SQL function EncryptByPassPhrase. So the encrypting is done as follows.
First a row is inserted in the TableA without any value in ColEncrypted. So ColEncrypted is NULL at insert time
An update statement is called to update the ColEncrypted column with the value to be encrypted as follows:
UPDATE TableA SET ColEncrypted = ENCRYPTBYPASSPHRASE(#passphrase,
#date,1,CONVERT(VARBINARY,PK))
WHERE PK = #Id
#passphrase is a nvarchar(50) value of length 12
#date is nvarchar(25) with date value in format yyyyMMdd. For e.g.
April 1, 2020 is '20200401'
PK is the primary key of the TableA and is an identity column of
data type int. It is used as authenticator. Thus each row has a
unique authenticator.
Decryption is done in a stored procedure as follows:
SELECT CONVERT(NVARCHAR,DECRYPTBYPASSPHRASE(#passphrase,ColEncrypted,1,CONVERT(VARBINARY,PK))) FROM
TableA WHERE PK = #Id
Now sometimes the decrypted value is NULL. Strangely the same value when encrypted again is decyrpted properly.
The one interesting thing I found is that the datalength of encrypted value for which the decrypted value is NULL is 67 whereas the datalength of encrypted value for which decryption occurs properly is 68, if this is something to consider.
Edit 1: (In response to Andrew's comments)
According to MS, VARBINARY when used in cast without specifying a size defaults to 30, which is sufficient enough. Look at the Remarks section in this article. https://learn.microsoft.com/en-us/sql/t-sql/data-types/binary-and-varbinary-transact-sql?view=sql-server-ver15
So that can't be a issue otherwise it would have failed each time. As for sysname, if you look at the example provided here https://learn.microsoft.com/en-us/sql/t-sql/functions/encryptbypassphrase-transact-sql?view=sql-server-ver15
, CreditCardId is used as authenticator by converting it to varbinary where a sysname datatype is expected. CreditCardId is a varchar datatype but nowhere I have found that int datatype cannot be used as long as I am converting it to varbinary.
Again as I mentioned this issue does not occur consistently. i.e. for the same input values for which the decryption fails, if I re-run the code for encryption, the decryption succeeds the next time. Therefore I suspect the issue is in the SQL Server engine. I have raised this question in SQL Product feedback but so far there is no response from them

String or binary data would be truncated. The statement has been terminated. System.Data.SqlClient.SqlException (0x80131904)

String or binary data would be truncated. The statement has been terminated.
System.Data.SqlClient.SqlException (0x80131904): String or binary data would be truncated
This exception throws when C#(model) try to save data record for column whose size defined less in SQL SERVER database table where value to pass to this column string length in greater.
To fix this error you only need to alter column of table in SQL SERVER database using SQL Server script.
Only increasing size of column in table works. No need to re deploy the application on PROD/TEST environment.
Please refer this sample below.
CREATE TABLE MyTable(Num INT, Column1 VARCHAR(3))
INSERT INTO MyTable VALUES (1, 'test')
Look at column1 its size is 3 but the given value is of length 4 so you would get the error.
To fix the error:
You should pass the string value less than or equal to it size ie., 3 characters like the below.
INSERT INTO MyTable VALUES (1, 'tes')
If you want to suppress this error
you can use set the below ansi_warnings parameter to off
SET ansi_warnings OFF
if we use ansi_warnings as OFF, the error would be suppressed and whatever can fit in the column, would be inserted, the rest would be truncated.
INSERT INTO MyTable VALUES (1, 'test')
The string 'tes' would be stored in your table and it won't return any error.

String or binary data would be truncated When try to insert to a float field

I'm working on SQL Server 2008.
I delete all data from a table and then I try to insert value to the table. Here's the code:
TRUNCATE TABLE [dbo].[STRAT_tmp_StratMain]
INSERT INTO [dbo].[STRAT_tmp_StratMain] ([FileNum])
SELECT [dbo].[STRAT_tmp_Customer].[NumericFileNumber]
FROM [dbo].[STRAT_tmp_Customer];
The FileNum in STRAT_tmp_StratMain is float number and is also index and can't be null.
NumericFileNumber is float and can be null but is never null and there are no duplicates in it (each row is unique number).
The table STRAT_tmp_StratMain contain much more fields but all can be null and also has a defualt values.
When I try to run this query I get the error:
Msg 8152, Level 16, State 4, Line 1 String or binary data would be
truncated. The statement has been terminated.
I tried also to do simply:
INSERT INTO [dbo].[STRAT_tmp_StratMain] ([FileNum]) Values (1);
Still get the same error.
Any ideas?
Thanks,
Ilan
I am not able to reproduce your issue. When I run this code on SQL Server 2008, I get no error:
DECLARE #tt TABLE (FileNum float NOT NULL);
INSERT INTO #tt (FileNum) VALUES (1);
Check the Default constraints on all the columns in your target table and make sure none of them would try to insert a string value that would truncated by the datatype limitations of the column.
example: SomeColumn varchar(1) DEFAULT 'Hello'
This due to the data you are trying to insert does not fit in the field: if you have a defined length of (say) 10 or 50 characters but the data you are trying to insert is longer than that.

Msg 8152, String or binary data would be truncated

I have this table:
CREATE TABLE Vendors
(
VendorID NUMERIC(10) NOT NULL,
VendorName CHAR(50) NOT NULL,
VendorAddress VARCHAR(30) NULL,
VendorCityName VARCHAR(20) NOT NULL,
VendorStateName CHAR(2) NOT NULL,
VendorZip VARCHAR(10) NULL,
VendorContactName CHAR(50) NOT NULL,
VendorContactPhone VARCHAR(12) NOT NULL,
VendorContactEmail VARCHAR(20) NOT NULL,
VendorSpecialty CHAR(20) NOT NULL
CONSTRAINT VendorsPK PRIMARY KEY (VendorID)
);
And this insert:
INSERT INTO Vendors(VendorID, VendorName, VendorAddress,
VendorCityName, VendorStateName, VendorZip, VendorContactName,
VendorContactPhone, VendorContactEmail, VendorSpecialty)
VALUES(151330, 'Hyperion', '77 West 66th Street', 'New York',
'NY', 10023, 'John Hinks', '212-337-6564',
'jhinks#hyperionbooks.com', 'Popular fiction')
Why does this statement yield the 8152 error?
VendorContactEmail is only 20 bytes. Your e-mail address on the first line (jhinks#hyperionbooks.com) is longer than that - 24 bytes. And many e-mail addresses will be longer. Who decided to only allow 20 characters in the e-mail address column? According to the standard, this should be VARCHAR(320) - 64 characters for <localpart> + 1 for # + 255 for <domain>.
As for the error message itself, finding the culprit is easier today than it was back then.
String or Binary data would be truncated: replacing the infamous error 8152
How to Force an Operation that Results in Truncation to Execute Anyway
Do you know what truncation is?
Do you know what is going to be truncated?
Is it your intention to truncate long data to fit?
If and and only if you answer YES to the above questions, you can force your inserts to ignore the warning and run anyway. If you answered no to any of the above, read on.
SET ANSI_WARNINGS OFF;
-- Your operation TSQL here.
SET ANSI_WARNINGS ON;
(source)
What is Truncation in this Context
Truncation is simply putting as much of a value as will fit into the column and then discarding any portion that doesn't fit. For example, truncating The quick brown fox jumps over the lazy dog to 13 characters would be The quick bro
Why would I receive this error message
You receive this error when you attempt to insert data that won't fit into a destination column definition because the data is too short.
I'm trying to insert many rows of data and want to determine which rows don't fit
Aaron's excellent answer notes that if you are running SQL Server 2019 or newer, you'll actually get a message that contains the column and value that won't fit - which is awesome! But if you aren't running a version that new, read on for tips.
If you receive this error message while attempting to bulk insert many rows of data, you might try splitting the insert into multiple inserts and running them separately to narrow down where the long value is.
Alternatively, you could insert the data into a new temp table and search said temp table for values that won't fit into your destination table.
--(insert into new temp table #Vendors)
INSERT INTO #Vendors(VendorID, VendorName, VendorAddress,
VendorCityName, VendorStateName, VendorZip, VendorContactName,
VendorContactPhone, VendorContactEmail, VendorSpecialty)
VALUES(151330, 'Hyperion', '77 West 66th Street', 'New York',
'NY', 10023, 'John Hinks', '212-337-6564',
'jhinks#hyperionbooks.com', 'Popular fiction')
Then query for rows that don't fit.
--(query for values that don't fit)
SELECT *,
LEN(VendorContactEmail) AS Length
FROM #Vendors
WHERE LEN(VendorContactEmail) > 20 --set your destination column length is here
See also LEN and DATALENGTH documentation for information on whitespace handling and binary data lengths.
You can also minimize the length of column values by using following expression:
LEFT(columnName, 250) + '...'
I tried and it works.

SQL Server - trying to convert column to XML fails

I'm in the process of importing data from a legacy MySQL database into SQL Server 2005.
I have one table in particular that's causing me grief. I've imported it from MySQL using a linked server and the MySQL ODBC driver, and I end up with this:
Col Name Datatype MaxLen
OrderItem_ID bigint 8
PDM_Structure_ID int 4
LastModifiedDate datetime 8
LastModifiedUser varchar 20
CreationDate datetime 8
CreationUser varchar 20
XMLData text -1
OrderHeader_ID bigint 8
Contract_Action varchar 10
ContractItem int 4
My main focus is on the XMLData column - I need to clean it up and make it so that I can convert it to an XML datatype to use XQuery on it.
So I set the table option "large data out of row" to 1:
EXEC sp_tableoption 'OrderItem', 'large value types out of row', 1
and then I go ahead and convert XMLData to VARCHAR(MAX) and do some cleanup of the XML stored in that field. All fine so far.
But when I now try to convert that column to XML datatype:
ALTER TABLE dbo.OrderItem
ALTER COLUMN XMLData XML
I get this message here:
Msg 511, Level 16, State 1, Line 1
Cannot create a row of size 8077 which
is greater than the allowable maximum
row size of 8060. The statement has
been terminated.
which is rather surprising, seeing that the columns besides the XMLData only make up roughly 90 bytes, and I specifically instructed SQL Server to store all "large data" off-row....
So why on earth does SQL Server refuse to convert that column to XML data??? Any ideas?? Thoughts?? Things I can check / change in my approach??
Update: I don't know what changed, but on a second attempt to import the raw data from MySQL into SQL Server, I was successfully able to convert that NTEXT -> VARCHAR(MAX) column to XML in the end..... odd..... anyhoo - works now - thanks guys for all your input and recommendations! Highly appreciated !
If you have sufficient storage space, you could try selecting from the VARCHAR(MAX) version of the table into a new table with the same schema but with XMLData set up as XML - either using SELECT INTO or by explicitly creating the table before you begin.
PS - it's a side issue unrelated to your problem, but you might want to check that you're not losing Unicode characters in the original MySQL XMLData field by this conversion since the text/varchar data types won't support them.
Can you ADD a new column of type xml?
If so, add the new xml column, update the table to set the new column equal to the XmlData column and then drop the XmlData column.
Edit
I have a table "TestTable" with a "nvarchar(max)" column.
select * from sys.tables where name = 'TestTable'
This gives a result containing:
[lob_data_space_id] [text_in_row_limit] [large_value_types_out_of_row]
1 0 0
yet I can happily save 500k characters in my nvarchar(max) field.
What do you get if you query sys.tables for your OrderItems table?
If your [text_in_row_limit] is not zero, try this, which should convert any existing in-row strings into BLOBs:
exec sp_tableoption 'OrderItems', 'text in row', 0
and then try to switch from nvarchar(max) to xml.
From BOL,
Disabling the text in row option or
reducing the limit of the option will
require the conversion of all BLOBs;
therefore, the process can be long,
depending on the number of BLOB
strings that must be converted. The
table is locked during the conversion
process.

Resources