cast varbinary max to varchar max

Benjoe 431 Reputation points
2021-05-13T20:33:16.163+00:00

I want to cast a varchar(max) to varbinary(max) and get the results with the hex numbers in front. I am doing
"SELECT
cast(Content as varchar(max))
FROM [dbo].[employeetable]
where Id = 216"
It gives me the correct value ="504B030414000600080000002100C7AF3C0FA10"
but i want "0x504B030414000600080000002100C7AF3C0FA10"
so I need the hex value '0x' in front.

Developer technologies Transact-SQL
{count} votes

Accepted answer
  1. Benjoe 431 Reputation points
    2021-05-13T21:26:07+00:00

    I have managed to solved it myself.
    SELECT '0x' + CAST(Content as varchar(max)) FROM [dbo].[employeetable] where Id = 216

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2021-05-13T21:28:02.717+00:00

    To get 0x in front, you need to say:

    SELECT convert(varchar(MAX), Content, 1)
    

    But I get a little worried when you say that you get the correct result with cast, save for the 0x. The default formatting is that the bytes are interpreted as charcaters, so

    SELECT cast(0x414243 AS varchar)
    

    produces ABC.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.