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.)
The output is:sql Code:
declare @num int, @out varchar(10) set @num = 2 set @out = case @num when 1 then char(65) when 2 then char(65) + char(65) when 3 then char(65) + char(65) + char(65) when 4 then char(65) + char(65) + char(65) + char(65) else char(65) + char(65) + char(65) + char(65) + char(65) end print 'output = |' + @out + '|' print 'length of output = ' + cast(len(@out) as varchar)
Notice that though the length of output is reported as 2, there are 3 spaces appended to it. So the actual length is 5.Code:output = |AA | length of output = 2
If we repeat the same thing with constants we get the results what we expect:
The output is:sql Code:
declare @num int, @out varchar(10) set @num = 2 set @out = case @num when 1 then 'A' when 2 then 'AA' when 3 then 'AAA' when 4 then 'AAAA' else 'AAAAA' end print 'output = |' + @out + '|' print 'length of output = ' + cast(len(@out) as varchar)
Notice that there are no spaces appended now. The length reported is still 2 and this is correct.Code:output = |AA| length of output = 2
Anyone knows the reason for this behaviour and how to get past this?




icon on the left of the post.
Reply With Quote