Wednesday, October 3, 2012

VARCHAR - when n is not specicfied (where n is the string length)

1. Varchar in Declare
----------------------------------------------------

When Varchar is used to declare a variable and the length is not specified, default  value is 1

For Example

declare @a varchar, --length of varchar is not specied
 @x varchar(5) --length of varchar is 5

set @a = 'xyz'set @x = 'xyz'
select len(@a) as len_not_specified, len(@x) as len_specified 

len_not_specified    len_specified 
--------------------       ------------------
1                     3


2. Varchar in CAST/CONVERT
--------------------------------------------------------------------
When Varchar is used in CAST or CONVERT and the length is not specified, default  value is 30

For Example:

select
len(replicate('a', 40)) as 'LEN_REPLICATE',
LEN(CONVERT(VARCHAR,replicate('a', 40))) AS 'Converted', --length of the varchar is not specified
LEN(CAST(replicate('a', 40) AS VARCHAR)) AS 'Cast' --length of the varchar is not specified


LEN_REPLICATE
     Converted    Cast
-------------     ---------    ----

40                30           30

No comments:

Post a Comment