3

I came across this scenario wherein I tried to concatenate a Char data type variable and a string but the results were pretty surprising.

declare @Var char(10) = 546875.5
set @Var = @Var + '100' 
select @Var

Output: 546875.5

I tried to increase the size of the variable , but still the same result.

declare @Var char(100) = 546875.5
set @Var = @Var + '100' 
select @Var

Output : 546875.5

When I reversed the concatenation, strings did concatenate :

declare @Var char(10) = 546875.5
set @Var = '100' + @Var 
select @Var

Output: 100546875.

Can anyone please help me solve this mystery.

Please note:: I understand that I can convert both before concatenating and that will serve the purpose. But I am not sure why this is not working.

TIA !!

1
  • try using Select CONCAT(@Var,'100') Commented Apr 2, 2018 at 5:12

3 Answers 3

3

@Var is right-padded with spaces because you used char instead of varchar. The spaces take up the entire available length, so there is nowhere for the '100' to be appended.

This can be seen with:

declare @Var char(100) = 546875.5 
set @Var = @Var + '100' 
select replace(@Var, ' ', 'X')

Change @Var to be varchar and you'll be fine. (And you need at least 11 characters).

declare @Var varchar(11) = 546875.5 
set @Var = @Var + '100' 
select @Var
Sign up to request clarification or add additional context in comments.

Comments

2

If you will use char data type, then you need to declare another char type variable and set concat value to that variable.

DECLARE @Var CHAR(10)='546875.5'
DECLARE @FinalVar CHAR(15)
SET @FinalVar=@Var + '100'
SELECT replace(@FinalVar,' ','')

Thanks.

Comments

1

All you need is to Trim the leading and trailing spaces before concatenating

declare @Var CHAR(100) = 546875.5
SET @Var = LTRIM(RTRIM(@Var)) + '100' 
SELECT @Var

Result

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.