7

I am using SQL Server 2008. I have made a new numeric column called unique_number and I would like to populate this column by concatenating two other numeric columns called site and number. The site column ranges from 1-31 and the values smaller than 10 do not have a zero in front of them. I Would like the following

Number      Site   unique_number
1234567      2       12345672
3456789      26      345678926

Using the + I have been able to get unique_number to be the sum of the two columns, but I want a concatenation to occur, not a summation. I've tried other suggestions using cast as varchar, but the select statement continues to give me errors. Is there a reasonable way to do this?

1
  • 2
    Why do you need to store this? Does Number always have 7 digits (and if not how will you know if 12345622 is 123456,22 or 1234562,2) Commented Jun 3, 2013 at 16:34

1 Answer 1

11

You should be able to cast both of the columns as a varchar and then concatenate them:

select number, site, 
  cast(number as varchar(50)) 
  + cast(site as varchar(2)) unique_number
from yt;

See SQL Fiddle with Demo

If you want to update your table, then you would just use the above in an update statement:

update yt
set unique_number = cast(cast(number as varchar(50)) 
                          + cast(site as varchar(2)) as int);

See Demo

Sign up to request clarification or add additional context in comments.

3 Comments

That was easy, thanks. Any clue about how to update my table at the same time? When I use the update statement errors occur because of the select statement
@user2448666 you will just use an UPDATE statement, see my edit with demo
I had to change int to numeric, but this worked perfectly. Thanks for the help.

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.