Tuesday, March 27, 2012

Concat with Auto-increment column

I have a column with consist of customer number.e.g.
c001
c002
c003

How do I add the character "c" to the auto-incremental number everything I add?

You mean you want to add "c" to your identity column? Well, you cannot prefix an identity column because the column must be numeric - how is it going to increment if it's alpha.

However, you can create a compute column that does the prefixing for you.

e.g.

Code Snippet

create table t(pk int identity primary key, custid as 'c'+right(1000+pk,3));

insert t default values;

insert t default values;

insert t default values;

select * from t;

|||

You can try this :

--create a function in that you can make all the conact or incrementations you need

USE [test]

GO

CREATE FUNCTION [dbo].[ConcAuto](@.incr INT)

RETURNS varchar(11)

AS

BEGIN

DECLARE @.Result varchar(11)

SET @.Result = 'C'+cast(@.incr as varchar(10))

RETURN

(

@.Result

)

END

GO

--then create a column , col, as computed column

CREATE TABLE [dbo].[aa](

[id] [int] IDENTITY(1,1) NOT NULL,

[col] AS ([dbo].[ConcAuto]([id])),

[name] [nchar](10) NULL

) ON [secondary]

GO

No comments:

Post a Comment