Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert text to image data type

I have a table that for some reason stores text as IMAGE. I can grab the data and read it using

SELECT CONVERT(NVARCHAR(MAX), CONVERT(VARBINARY(MAX), column,2)) FROM table

Now I need to insert data back in to the table. I've tried

SELECT CONVERT(IMAGE, CAST('TEST TEXT' AS VARBINARY(MAX)))

But when I test converting it back using

SELECT CONVERT(NVARCHAR(MAX), CONVERT(VARBINARY(MAX), CONVERT(IMAGE, CAST('TEST TEXT' AS VARBINARY(MAX))),2))

It returns 䕔呓吠塅 which is obviously not right as it should return "TEST TEXT"

What am I doing wrong here?

like image 477
AlexF11 Avatar asked Jul 11 '26 15:07

AlexF11


2 Answers

The text you're trying to store is encoded as binary ASCII characters. You're trying to convert it back into a Unicode text string, which isn't what it originally was, therefore you're getting back garbled text.

Change your source text string into a Unicode string by adding N in front of it:

SELECT CONVERT(NVARCHAR(MAX), CONVERT(VARBINARY(MAX), CONVERT(IMAGE, CAST(N'TEST TEXT' AS VARBINARY(MAX))),2))

It should return the correct text. Tested this on SQL Server 2008

like image 168
Froopy Avatar answered Jul 18 '26 15:07

Froopy


You can use this one:

SELECT CONVERT(**VARCHAR(MAX)**, CONVERT(VARBINARY(MAX), **CAST('TEST TEXT' AS IMAGE)**,**0**))

Basically, you were not consistent with your character type conversions. In some parts you used NVarChar and some parts Varchar. Also, the number 2 at the end is affecting the result. In you Convert statements, when you don't specify the code, default value (0) is used. So if you are converting it back, you should use the same code.

like image 45
Sparrow Avatar answered Jul 18 '26 15:07

Sparrow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!