Tuesday, June 28, 2016

Concatenate 2 Integers Into 1 Varchar (SQL)

Yesterdays Just A Tip Felt so good, I thought I would do it again today.  Twice in one week.  You guys & gals get a great tip, while I get another notch under my belt.  Win.  Win.

Today's coding issue involves 2 Integer fields that need to be concatenated into 1 big field and that field needs to be Varchar.  To accomplish this, you will need to Cast each  Integer as a Varchar then concatenate them.
For Example, in an SQL table called tblPetOwners you have 2 fields (OwnerNumber & PetNumber)   which are Integers and wish to join them with an '&' in between them.  To do this, you have to CAST them both as Varchar before concatenating them.  Below is the best way I have came across to accomplish this task and I show you the data in the table, the code itself, followed by the results.

Table tblPetOwners Data:

Example Code:

+ ' & ' + 
CAST(PetNumber AS VARCHAR(10) ) OwnerAndPet, OwnerNumber, PetNumber 
FROM tblPetOwners

Results Data:

223122 & 543224223122543224
643233 & 235432643233235432
332342 & 654523332342654523

If you like this post and want to see more, follow me on my website www.chadcompton.com
Or if you prefer...

No comments:

Post a Comment

Drop me a line.