How to convert a column value from varbinary(max) to varchar in human-readable form?
-
3i want varchar since the value was isterted from string value.. I mean to read what was written..Bilgin Kılıç– Bilgin Kılıç2010-07-20 12:43:59 +00:00Commented Jul 20, 2010 at 12:43
-
2People seem to be coming across this from search engines and based on the voting the style 2 parameter seems more commonly required but this does not do what your original requirement wasMartin Smith– Martin Smith2019-10-08 06:58:57 +00:00Commented Oct 8, 2019 at 6:58
8 Answers
The following expression worked for me:
SELECT CONVERT(VARCHAR(1000), varbinary_value, 2);
Here are more details on the choice of style (the third parameter).
5 Comments
"Converting a varbinary to a varchar" can mean different things.
If the varbinary is the binary representation of a string in SQL Server (for example returned by casting to varbinary directly or from the DecryptByPassPhrase or DECOMPRESS functions) you can just CAST it
declare @b varbinary(max)
set @b = 0x5468697320697320612074657374
select cast(@b as varchar(max)) /*Returns "This is a test"*/
This is the equivalent of using CONVERT with a style parameter of 0.
CONVERT(varchar(max), @b, 0)
Other style parameters are available with CONVERT for different requirements as noted in other answers.
4 Comments
SELECT CAST('This is a test' AS VARBINARY(100)) which is 0x5468697320697320612074657374 in my default collation and converts it back to the varchar string. Gunjan's answer returns the hex representation as a string ('5468697320697320612074657374') Presumably this interpretation is correct for the OP's need as they accepted it.CONVERT has a style parameter to select the way you want (my interpretation is the default style) So this answer may not be what you need for your use case at the moment but it is correct for other use cases. Including the original questioner's who specified "human readable form" not hex.Try this
SELECT CONVERT(varchar(5000), yourvarbincolumn, 0)
2 Comments
I tried this, it worked for me:
declare @b2 VARBINARY(MAX)
set @b2 = 0x54006800690073002000690073002000610020007400650073007400
SELECT CONVERT(nVARCHAR(1000), @b2, 0);
3 Comments
Have a go at the below as I was struggling to
bcp "SELECT CAST(BINARYCOL AS VARCHAR(MAX)) FROM OLTP_TABLE WHERE ID=123123 AND COMPANYID=123"
queryout "C:\Users\USER\Documents\ps_scripts\res.txt" -c -S myserver.db.com -U admin -P password
Reference: original post