milner236
milner236

Reputation: 37

Auto Increment with Numbers and Letters

I am trying to auto increment with numbers and letters. It should look like this:

KH001
KH002
KH003
etc..

I've looked at a couple of articles and other Stack Overflow questions but couldn't manage to understand as SQL is my much weaker side.

I have created a column named string that had varchar(50) data type and a fixed value of KH. I created a second column named string2 that had int data type and auto increment by 1 that works.

Then I added the following line to my query:

string + string2 as <column name>

Received an error saying I couldn't convert 'KH' to int.

Upvotes: 0

Views: 2238

Answers (2)

GuidoG
GuidoG

Reputation: 12014

here are 2 simple methods you can use

declare @string varchar(10) = 'KH'
declare @string2 int = 1

select concat(@string, @string2),
       @string + convert(varchar, @string2)

More info about the Concat funtion

You can also add a computed column in your table that does this for you,

    alter table yourtable 
    add mycolumn as concat(string, string2)

Read more about computed columns here

To get zeros left of your number, you can do this

concat(@string, RIGHT ('00000' + Convert(nvarchar(20), @string2), 5))

Upvotes: 2

Joel Coehoorn
Joel Coehoorn

Reputation: 415620

string + cast(string2 as varchar(10)) as <column name>

Upvotes: 0

Related Questions