Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting from base64 string to varbinary(max) in SQL Server

I have PDF documents stored in my table as binary, the column that stores the bytes for the PDFs is type varbinary(max). I want to update one record with an updated document in SQL Studio, the way I am attempting to accomplish this is like below

UPDATE table
SET file_bytes=CONVERT(varbinary(max),'JVBERi0xLjYNCiW2JqDQo8PC9UeX...0YNCg==') --this is a base64 string
WHERE id='73c75254-ad86-466e-a881-969e2c6e7a04';

The query runs, but when I try to download the document (via the website), it throws an error message that reads PDF header signature not found.

Is this conversion even possible?

like image 397
esausilva Avatar asked Sep 17 '14 17:09

esausilva


People also ask

Can we convert varchar to varbinary in SQL Server?

SqlException: 'Implicit conversion from data type varchar to varbinary(max) is not allowed.

What is the max size of Varbinary 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.

What does Varbinary mean in SQL?

VarBinary is a variable width data type. The syntax for declaring Binary variable is varbinary(n) , where n defines the maximum size in bytes. The varbinary data type uses actual length of the data entered + 2 bytes as the storage.

What is the difference between Varbinary and image?

VARBINARY(MAX) - Binary strings with a variable length can store up to 2^31-1 bytes. IMAGE - Binary strings with a variable length up to 2^31-1 (2,147,483,647) bytes.


1 Answers

It is possible by using the approach described here : https://blogs.msdn.microsoft.com/sqltips/2008/06/30/converting-from-base64-to-varbinary-and-vice-versa/

It's a two-step process, first you declare a variable :

declare @str varchar(max) = '/9j/4AAQSkZJRgABAQEAAAAAAAD/==';

Then you can use the variable in your SQL statement as follow :

INSERT INTO Documents (Name, Body, MIMEType)
VALUES('12446_photo.jpg', cast(N'' as xml).value('xs:base64Binary(sql:variable("@str"))', 'varbinary(max)'), 'image/jpeg');
like image 161
Marc-André Gosset Avatar answered Sep 18 '22 02:09

Marc-André Gosset