WHAT IS DIFFERNCE B/W CHAR AND VARCHAR IN THIS PROGRAMM

  • I WROTE CODE LIKE THIS ,

    --reversing the given string

    Declare @len int,@str varchar(50),@rev varchar(50)='',@A char(50)=''

    set @str='WelCome to the SQL'

    set @len=len(@str)

    while(@len > 0 )

    begin

    set @rev = RIGHT(left(@str,@len),1)

    set @A=@A+@rev

    set @len=@len-1

    end

    print @A

    --it is not giving any output and also not concating @a and @rev

    Declare @len int,@str varchar(50),@rev varchar(50)='',@A varchar(50)=''

    set @str='WelCome to the SQL'

    set @len=len(@str)

    while(@len > 0 )

    begin

    set @rev = RIGHT(left(@str,@len),1)

    set @A=@A+@rev

    set @len=@len-1

    end

    print @A

    --it is correct output

    But difference is ,i declared @A char(50) in first code,

    and @A varchar(50) in second code,just difference is char and varchar,

    but char is not giving output,varchar is giving output.

    what is difference b/w char and varchar in this case only

  • The difference is the way this statement works:-

    set @A=@A+@rev

    When it is declared as a CHAR, it is a fixed 50 bytes, so you are trying to put 50 bytes + 1 byte into a 50 byte variable, so you are getting truncation.

    When it is a VARCHAR, you are putting 1 byte + 1 byte into something that is a maximum of 50 bytes, then the next time you are putting 2 bytes + 1 byte into 50 etc etc.

    PS. I hope this wasn't a homework question that you were supposed to work out for yourself!

  • As advised, it's due to char's being padded to their full length, even with empty strings.

    Also, are you aware there's a built in function called REVERSE? 🙂

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply