Results 1 to 17 of 17

Thread: [SQL Server 2005] Mysterious problem with CASE statement

Threaded View

  1. #1

    Thread Starter
    VB Addict Pradeep1210's Avatar
    Join Date
    Apr 2004
    Location
    Inside the CPU...
    Posts
    6,614

    [SQL Server 2005] Mysterious problem with CASE statement

    Hi,
    When I perform some calcualtion in a case statement, it appends spaces randomly to the end of it. (From what I observed, it tries to make the length of the output equal to the longest possible value from all case conditions.)
    sql Code:
    1. declare @num int, @out varchar(10)
    2. set @num = 2
    3. set @out =  case @num
    4.                 when 1 then char(65)
    5.                 when 2 then char(65) + char(65)
    6.                 when 3 then char(65) + char(65) + char(65)
    7.                 when 4 then char(65) + char(65) + char(65) + char(65)
    8.                 else char(65) + char(65) + char(65) + char(65) + char(65)
    9.             end
    10. print 'output = |' + @out + '|'
    11. print 'length of output = ' + cast(len(@out) as varchar)
    The output is:
    Code:
    
    output = |AA   |
    length of output = 2
    
    Notice that though the length of output is reported as 2, there are 3 spaces appended to it. So the actual length is 5.


    If we repeat the same thing with constants we get the results what we expect:
    sql Code:
    1. declare @num int, @out varchar(10)
    2. set @num = 2
    3. set @out =  case @num
    4.                 when 1 then 'A'
    5.                 when 2 then 'AA'
    6.                 when 3 then 'AAA'
    7.                 when 4 then 'AAAA'
    8.                 else 'AAAAA'
    9.             end
    10. print 'output = |' + @out + '|'
    11. print 'length of output = ' + cast(len(@out) as varchar)
    The output is:
    Code:
    
    output = |AA|
    length of output = 2
    
    Notice that there are no spaces appended now. The length reported is still 2 and this is correct.


    Anyone knows the reason for this behaviour and how to get past this?
    Last edited by Pradeep1210; Jul 14th, 2009 at 04:12 AM.
    Pradeep, Microsoft MVP (Visual Basic)
    Please appreciate posts that have helped you by clicking icon on the left of the post.
    "A problem well stated is a problem half solved." — Charles F. Kettering

    Read articles on My Blog101 LINQ SamplesJSON ValidatorXML Schema Validator"How Do I" videos on MSDNVB.NET and C# ComparisonGood Coding PracticesVBForums Reputation SaverString EnumSuper Simple Tetris Game


    (2010-2013)
    NB: I do not answer coding questions via PM. If you want my help, then make a post and PM me it's link. If I can help, trust me I will...

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width