Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert varbinary data into SQL Server database

I have this table:

   (<NUM_TRF int    ,<NAME, varchar(255),>    ,<DESCRIPTION, text,>    ,<REPORT, varbinary(max),>) 

I try to create a script in SQL Server 2008, in order to insert a line on my local database,

INSERT INTO [MY_DB_APP].[dbo].[CONNECT_USER] VALUES(1, 'name', 'description', Cast('wahid' As varbinary(max)) ) GO 

but I get this error:

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

like image 405
Wahid Gazzah Avatar asked Aug 25 '14 13:08

Wahid Gazzah


People also ask

What is VARBINARY data type in SQL Server?

The VARBINARY type is similar to the VARCHAR type, but stores binary byte strings rather than non-binary character strings. M represents the maximum column length in bytes. It contains no character set, and comparison and sorting are based on the numeric value of the bytes.

When would you use VARBINARY data type?

The VARBINARY data type holds variable-length binary data. Use this type when the data is expected to vary in size. The maximum size for VARBINARY is 8,000 bytes.

What is VARBINARY Max in SQL Server?

varbinary [ ( n | max) ] Variable-length binary data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of the data entered + 2 bytes.

How can I see VARBINARY data in SQL Server?

INSERT INTO #TempTable(PK, VarBinaryColumn) SELECT PK, VarBinaryColumn FROM dbo. YourPermanentTable; If you need to convert the varbinary data back to the original file text format in T-SQL, you can use CAST or CONVERT to convert to varchar or nvarchar as long as the data was originally ASCII or Unicode.


1 Answers

Two issues:

Issue #1: don't use TEXT anymore - it's deprecated. Use a VARCHAR(n) with a suitable size of n, or if you really must (only if you REALLY must), use VARCHAR(MAX)

CREATE TABLE dbo.CONNECT_USER (     NUM_TRF int,     NAME varchar(255),     DESCRIPTION varchar(1000),     REPORT varbinary(max) ) 

I would personally also avoid writing EVERYTHING IN ALL CAPS - this just makes it so much harder to read! And I would try to avoid very generic column names like Name or Description - those are not very intuitive, and might collide with other table's columns and / or with SQL Server reserved keywords. Try to use more expressive, more context-related column names that make sense in your environment (ConnectUsername or whatever)

Issue #2: when doing an INSERT, I would recommend to always define the column you want to insert into. This avoids unpleasant surprises when a table is restructured or new columns are added:

INSERT INTO [MY_DB_APP].[dbo].[CONNECT_USER](NUM_TRF, NAME, DESCRIPTION, REPORT) VALUES(1, 'name', 'description', CAST('wahid' AS VARBINARY(MAX))) GO 
like image 98
marc_s Avatar answered Sep 24 '22 02:09

marc_s