• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 302
  • Last Modified:

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
0
Morpheus7
Asked:
Morpheus7
1 Solution
 
Jim HornMicrosoft SQL Server Developer, Architect, and AuthorCommented:
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

0
 
PortletPaulCommented:
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)
0
 
Morpheus7Author Commented:
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
0
 
Scott PletcherSenior DBACommented:
Seems straightforward:

SELECT LEFT(key_column, LEN(key_column) - 4) + CAST(RIGHT(key_column, 4) + 1 AS varchar(4))
FROM (
    SELECT 'AB345678928976' AS key_column
) AS test_data
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now