Link to home
Start Free TrialLog in
Avatar of Morpheus7
Morpheus7

asked on

Combine varchar and int results together

Hi,

We receive an alphanumeric string of 14 characters of data from our customers and we need to increment the last four numeric digits. The string is in the form of AB345678928976. We use the last four digits in a variable and work on it this way. Which works fine as I have set the variable as type INT. The problem is, we need now to combine them back together with the new last 4 digits and the original first 10 digits. So if we had done this on the example above, the last four digits would be different.

Any help would be appreciated.

Thanks
Avatar of Jim Horn
Jim Horn
Flag of United States of America image

You'll have to CAST the int as a varchar in order to concatenate it with another varchar.

Something like...
Declare @val varchar(25) = 'AB34567892', @int int = 8976
SELECT @val + CAST(@int + 1 as varchar(4))

Open in new window

select CONCAT('AB34567892', 8976)

Jim's answer is absolutely fine, works in all sql server versions, this is just an alternative. a few nice things about CONCAT():

Available from SQL 2012 on, you can use the handy dandy CONCAT()

a. it will do the conversion for you
b, it handles NULLs gracefully
c. it is "sql standard" so code is more transportable (in theory, i'd not worry over this too much)
Avatar of Morpheus7
Morpheus7

ASKER

Hi,
Many thanks for the replies.

To do the work, I have split the original varchar string into 2 variables, one is the last four which will always be digits, but the original first ten characters are in a varchar variable. So being able to recombine them after the work is done on the last four back into a varchar column is proving tricky
ASKER CERTIFIED SOLUTION
Avatar of Scott Pletcher
Scott Pletcher
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial