Conversion of Image type to Text - sql

I'm having some trouble converting the below Image data type to text;
0x1F8B0800FC7E1F3000FF758FCB6EC2301045F748FCC3FC00D524518A0AAB967655D10D5D7AE324E360C9B1A3B179B4887FAF431254FAD8F83173E6DE3B27C14125425AAF2F47D9D6499AA742B16B021D03888A94C29350CE865098E9243E51287FD0DEC3236B6996E74B3111AA7115B18595DBB12686373A0CBDA867B511AADC4AF61452D87C34851B27B371F20AE0ADC6052B9D711C1308A60A45CD441645617684CB5FA534CF3B6DB12B13D14AAE446BA4B6DD2A4116D93D42BF438AF0BE2558EB929D772AC0CB3106B035C186781FDDD7529BC21DE36D651DFF5BE9A1744D6B2850052DBB92BCD7B686A607C97776D3C92648EE081916223A428A389FE1C30C73C07C91CD17E9BC075757B17FD12CEFD1F56831FA52354C0CFD588A213D346E3FB67088A33F099CEA3BD00CE080DC21C2EB530F3E531FE60772AB52FD0D7DD7397F01A585816657020000
I have tried casting as varbinary and then casting that to nvarchar, but get what looks like Unicode characters;
select top 1 cast(cast(body as varbinary(max)) as nvarchar(max)) from dbo.messagedata
How can I convert the above Image data into readable text?

Related

Encrypting and Decrypting String Using SQL's EncryptByPassPhrase

I have a need to Encrypt text, transmit the encrypted text, and decrypt the text ... using SQL.
I tried EncryptByPassPhrase which returns a VARBINARY. I convert it to VARCHAR (for easier transmitting), and when I try to convert it back to VARBINARY, it fails. From what I can see, the CONVERT from VarBinary to VarChar, truncates the string, appears like the second half of the VarBinary value gets dropped when converting to VarChar. So when converting back from that VarChar value, it is incomplete and fails.
Here is sample code:
DECLARE #binEncryptedText VARBINARY(MAX) = EncryptByPassPhrase('Password', 'My Text')
DECLARE #strEncryptedText VARCHAR(MAX) = CONVERT(VARCHAR, #binEncryptedText, 2)
DECLARE #binDecryptedText VARBINARY(MAX) = CONVERT(VARBINARY, #strEncryptedText, 2)
DECLARE #strDecryptedText VARCHAR(MAX) = CONVERT(VARCHAR, DecryptByPassPhrase('Password', #binDecryptedText))
SELECT 1 As RowNumber,
#binEncryptedText AS EncryptedBinary,
#strEncryptedText AS EncryptedBinaryAsText
UNION
SELECT 2 As RowNumber,
#binDecryptedText AS EncryptedBinary,
#strDecryptedText AS EncryptedBinaryAsText
As you can see in the screenshot of my results above... In Row #1, the Binary that was converted to Text ... is shorter than the original Binary (truncated roughly halfway). So when converting that truncated text back to Binary, it fails to return the complete value ... which then causes the Decrypt to fail.
How can I get the encrypted text's VarBinary converted to "text" and then have the "text" converted back to the correct VarBinary value so it can be decrypted?
MSSQL has a well hidden Base64 encoder and decoder - within the XML subsystem. Convert the encrypted varbinary to Base64 for transmission, it will become an ASCII string, transmit the string, then decode back to a varbinary. The encoder/decoder is an XPath function, so you need an XML context to run it, but you can provide a dummy one. So the code for encoding goes:
cast('' as xml).value('xs:base64Binary(sql:variable("#b"))', 'varchar(max)')
where #b is your varbinary.
To decode:
cast('' as xml).value('xs:base64Binary(sql:variable("#s"))', 'varbinary(max)')
where #s is the Base64 string.
It's kind of funky that the encoder and the decoder is the same function, but I guess it knows what to do by the datatype of the argument. I haven't used this technique extensively myself, but I've tried it and it worked as expected. MSSQL 2019.
You can also use xs:hexBinary to encode the binary data as hex. Base64 representation is smaller, though; 4 characters for 3 bytes vs. 2 for 1.
So I actually ended up figuring out what my problem was. In SQL, some of my commands were "incomplete" ... in a manner of speaking.
DECLARE #binEncryptedText VARBINARY(MAX) = EncryptByPassPhrase('Password', 'My Text')
DECLARE #strEncryptedText VARCHAR(MAX) = CONVERT(VARCHAR(MAX), #binEncryptedText, 2)
DECLARE #binDecryptedText VARBINARY(MAX) = CONVERT(VARBINARY(MAX), #strEncryptedText, 2)
DECLARE #strDecryptedText VARCHAR(MAX) = CONVERT(VARCHAR(MAX), DecryptByPassPhrase('Password', #binDecryptedText))
SELECT 1 As RowNumber,
#binEncryptedText AS EncryptedBinary,
#strEncryptedText AS EncryptedBinaryAsText
UNION
SELECT 2 As RowNumber,
#binDecryptedText AS EncryptedBinary,
#strDecryptedText AS EncryptedBinaryAsText
As you can see in the code above, in the CONVERT statements ... I needed to add the additional "size" of the returning VARCHAR I was converting to. Previously my convert commands said ...
...CONVERT(VARCHAR, ...
... when they should have said ...
...CONVERT(VARCHAR(MAX), ...
Once I made that change, the returning HEX String was no longer being truncated.

convert big varbinary into text field (MSSQLSERVER)

I try to fetch a big textcontent (<8000 chars) of a varbinary(max) field as follow:
CAST(varbinary_as_text AS VARCHAR(10000)) AS varbinary_as_text
I get the following error due the varchar is limited to 8000 chars:
java.sql.SQLException: The size (10000) given to the type 'varchar' exceeds the maximum allowed for any data type (8000).
How to fetch the text (> 8000 chars) content of a varbinary(max) field ?
Cast it as text
CAST(varbinary_as_text AS TEXT) AS varbinary_as_text
OR
Cast it as varchar(max)
CAST(varbinary_as_text AS varchar(max)) AS varbinary_as_text

Conversion failed when converting the nvarchar value 'AAAR78509883' to data type int

I have a nvarchar column in one of my tables that I have imported from Access. I am trying to change to an int. To move to a new table.
The original query:
insert into members_exams_answer
select
ua.members_exams_id, ua.exams_questions_id,
ua.members_exams_answers_value, ua.members_exams_answers_timestamp
from
members_exams as me
full join
UserAnswers1 as ua on me.members_exams_username = ua.members_exams_id
full join
exams_questions as eq on eq.exams_questions_id = ua.exams_questions_id
This throws an error:
Conversion failed when converting the nvarchar value 'AAAR78509883' to data type int.
I have tired:
select convert (int, UserAnswers1.members_exams_id)
from UserAnswers1
and
select cast(members_exams_id as integer) int_members_exams_id
from UserAnswers1
and
select cast (members_exams_id as int)
from UserAnswers1
All result in the same error
Conversion failed when converting the nvarchar value 'AAAR78509883' to data type int.
Clearly you are trying to convert data that is alphanumeric to an int and that cannot be done.
Looking at your data why are you insisting on converting it to an int when it cannot be an int? Why not just process it as an nvarchar?
Your problem could be systemic where all data has a leading alpha characters that you need to strip out (and hopefully the same number of alpha characters)
In that case use a substring to strip off the alphas (this assumes the name number of alphabetic characters in each record). Or use a varchar or nvarchar field instead of an int. If the number of leading characters varies or if they can be leading or trailing or some other combination, it will much more complex to fix than we can probably describe on the Internet.
The other possibility is that you simply have some bad data. In which case identify the records which are not numeric and fix them or null the value out if they cannot be fixed. This happens frequently when you have stored the data in an incorrect datatype.

Conversion fails when trying to Convert string to int

I have some sales numbers in a string column that I need to convert to some format so that i can calculate them with each other but I get this error while trying to convert them.
Conversion failed when converting the varchar value '-6.353,35' to data type int.
I'm not allowed to lose any money by rounding it up. It doesnt mather but in what type i convert as long as im not rounding them up. What's your thoughts?
For example i have -6.353,35 and 300,30 and i want to sum them too -6.053,05
try this...
select convert(int,convert(float,replace('-6.353,35',',','')))
as there are (,) Commas it cannot be converted to float,so remove the (,)commas after converting to float we can convert to int
If you want decimal values, then you should use float
select convert(float,replace('-6.353,35',',',''))
Edit
Like #marc_s suggested, it is preferred to use decimal rather than float
select convert(decimal,replace('-6.353,35',',',''))
Firstly, you want to convert this to a decimal value, not an int, as you will lose anything after decimal point otherwise.
The problem here is the separators that are being used when storing your values.
With your numbers, you have points . to represent thousand separators and commas , to represent decimal points.
To enable you to convert the value to a valid decimal you need to have it in a format that SQL Server can process.
A simple way to do this would be to remove/replace the problem characters before trying to convert the value:
DECLARE #val AS VARCHAR(10) = '-6.353,35'
-- step 1: remove thousand separator
SET #val = REPLACE(#val, '.', '')
SELECT #val AS RemoveThousandSeparator
-- step 2: replace decimal separator with decimal point
SET #val = REPLACE(#val, ',', '.')
SELECT CONVERT(DECIMAL(18,2), #val) AS DecimalPointAdded
-- to do it in one statement:
SET #val = '-6.353,35'
SELECT CONVERT(DECIMAL(18,2),
REPLACE(REPLACE(#val, '.', ''), ',', '.')) AS NumericeRepresentation
Aside from this, you would be much better off storing numeric values in the correct format in the first place to avoid this kind of workaround.

Varbinary and image conversion

I have an Access front end that links to a SQL Server backend.
There are 3 fields in a table that I am trying to convert to text from the backend:
o_name varbinary(2000)
O_PropertyBinary1 varbinary(2000)
O_PropertyBinary2 image
I can convert the o_name field using:
convert(varchar([max]),[O_Name])
and that works fine.
e.g. 4153534554 = ASSET
However, what can I use for the other two fields, as it seems I can't convert an image field and converting the O_PropertyBinary1 comes out with garbage characters.
The output is depended on the stored data an the appropriate conversion.
If the stored data is binary e.g. Bitmaps, converting to text will never give a usable result.
If data stored is text, it could be Varchar or NVarchar and kind conversion is depending.
in the example below VC_VB2NVarchar and VC_IMG2NVarchar would display your described garbage characters
Declare #tab Table(nvc NVarchar(100),vc Varchar(100)
,img image,vb VarBinary(200),img2 image,vb2 VarBinary(200))
Insert into #tab (nvc,vc) Values ('123456789','123456789')
Update #tab set vb=Convert(VarBinary(200),nvc),img=Convert(Image,Convert(Varbinary(max),nvc))
,vb2=Convert(VarBinary(200),vc),img2=Convert(Image,Convert(Varbinary(max),vc))
Select nvc,vc
,CONVERT(Nvarchar(100),vb) as NVC_VB2NVarchar
,CONVERT(Varchar(200),vb) as NVC_VB2Varchar
,CONVERT(Nvarchar(100),Convert(VarBinary(max),img)) as NVC_IMG2NVarchar
,CONVERT(Varchar(200),Convert(VarBinary(max),img)) as NVC_IMG2Varchar
,CONVERT(Nvarchar(100),vb2) as VC_VB2NVarchar
,CONVERT(Varchar(200),vb2) as VC_VB2Varchar
,CONVERT(Nvarchar(100),Convert(VarBinary(max),img2)) as VC_IMG2NVarchar
,CONVERT(Varchar(200),Convert(VarBinary(max),img2)) as VC_IMG2Varchar
from #Tab