April 11, 2011

SQL Server: Increment an AlphaNumeric Number‏




Your columns may have a categorization scheme in the form of an alphanumeric number. and it may be needed to have a customized incremental value for this scheme. Consider that you want to have numbers in the series like ABC1, ABC2, ABC3  etc. In SQL Server, there can be many methods to do this.

In this post, I will show two methods to increment an Alphanumeric Number in SQL Server

Method 1 : Derive it in a SELECT statement

sqlserver-alpha-numeric-increment

declare @t table(id int identity(1,1), names varchar(100))
insert into @t(names)
select 'test1' union all
select 'test2' union all
select 'test3' union all
select 'test4' union all
select 'test5'

select 'ABC'+CAST(id as varchar(10)) as id,names from @t

The above method concatenates the string with the identity column. This produces the following results:

sqlserver-alpha-numeric

Method 2 : Use Derived column in the table

sqlserver-alpha-numeric-increment-new

declare @t table(id int identity(1,1),
    alpha_id as 'ABC'+CAST(id as varchar(10)), names varchar(100))
insert into @t(names)
select 'test1' union all
select 'test2' union all
select 'test3' union all
select 'test4' union all
select 'test5'

select * from @t

Using this method, the T-SQL code concatenates the string ABC with identity column as soon as data is added to the table.

OUTPUT

alpha4


Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Madhivanan,an MSc computer Science graduate from Chennai-India, works as a works as a Lead Subject Matter Expert at a company that simplifies BIG data. He started his career as a developer working with Visual Basic 6.0, SQL Server 2000 and Crystal Report 8. As years went by, he started working more on writing queries in SQL Server. He now has good level of knowledge in SQLServer, Oracle, MySQL and PostgreSQL as well. He is also one of the leading posters at www.sqlteam.com and a moderator at www.sql-server-performance.com. His T-sql blog is at http://beyondrelational.com/blogs/madhivanan

 
  Feedback:

comments

0 Responses to "SQL Server: Increment an AlphaNumeric Number‏"
 

Copyright © 2009-2014 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions