开发者

using cast or convert function in stored procedure

why we have to use cast or cnvert function in 2nd and 3rd selecct statement, and what we achieve by casting or converting it to varchar, what varchar data type do in it exactly?

DECLARE @mybin1 binary(5), @mybin2 binary(5)
SET @mybin1 = 0xFF
SET @mybin2 = 0xA5
-- No CONVERT or CAST function is necessary because this example 
-- concatenates two binary strings.
SELECT @mybin1 + @mybin2
-- A CONVERT or CAST function is necessary because this example
-- concatenates two binary strings plus a space.
SELECT CONVERT(varchar(5), @mybin1) + ' ' 
    + CONVERT(varchar(5), @mybin2)
-- Here is the same conversi开发者_开发技巧on using CAST
SELECT CAST(@mybin1 AS varchar(5)) + ' ' 
    + CAST(@mybin2 AS varchar(5))


Casting it to a VarChar converts the data from a sequence of bytes to character text. As Flip says, you can't directly concatentate the different types. Typically binary strings are for images, videos, streams, etc, where as varchar is usually string data like what is found in a text file.


because in your select statement you are concatenating the the variables with space(' ') which is a type of varchar to you need to cast them to get the desired results.

in a sense you it might give you an error because your data types are different/incompatible.


Since they are different data types, you can't directly concatenate binary data and text strings (varchar), which is why you need either the CAST or the CONVERT.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜