views:

38

answers:

1

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!

A: 

Yes, it's the exact code to produce the issue. My Sql server version is:

Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86) Jul 9 2008 14:43:34 Copyright (c) 1988-2008 Microsoft Corporation Developer Edition on Windows NT 5.1 (Build 2600: Service Pack 3)

ProductVersion=10.0.1600.22
ProductLevel =RTM
Edition =Developer Edition

See screenshot link: http://www.freeimagehosting.net/uploads/63e705a604.png

xaxie