Last byte missing when casting from varbinary to varchar

Posted by xaxie on Stack Overflow See other posts from Stack Overflow or by xaxie
Published on 2010-04-09T01:31:17Z Indexed on 2010/04/09 1:33 UTC
Read the original article Hit count: 412

Filed under:
|

I got the last byte losing when converting varbinary to varchar in some case. For example:

DECLARE @binary varbinary(8000),
        @char varchar(8000)
set @binary = 0x000082
set @char = CAST(@binary as varchar(8000))
select BinaryLength=DATALENGTH(@binary), CharLength=DATALENGTH(@char)

The result is

BinaryLength   CharLength
    3              2

The affected byte value is from 0x81 - 0xFE.

The stranger thing is that if I use varchar(MAX) instead varchar(8000) when casting, there is no any problem.

Could someone tell me the root cause of the issue?

PS: I run the sql in MS SQL server 2008.

Thanks!

© Stack Overflow or respective owner

Related posts about tsql

Related posts about sql-server-2008