Monday, February 4, 2013

Create table with string identity column




First, You can not directly create a string IDENTITY column in table definition, But we can achive this following ways

1. We can create a compute column using the IDENTITY column. Compute column means evaluate the value using expression.


Create Table TableName1
(
ID int IDENTITY(1,1),
ComputeStrID As 'AnyStrValue' + CAST( ID as Varchar),
AnyOtherColumn varchar(12)
);


insert into TableName1(AnyOtherColumn) values ('Test')
insert into TableName1(AnyOtherColumn) values ('Test2')
insert into TableName1(AnyOtherColumn) values ('Test3')
insert into TableName1(AnyOtherColumn) values ('Test4')


select * from TableName1

Constrain : Only one identity column per table is allowed.



2. In Code, we can manipulate the db identity value while showing the result in screen, somethink like

String.Format("0{1:000}","AnyStrValue", db.ID)
code is in C#



1 comment:

Please include your thoughts/suggestion to make it as a better blog. If you find it useful, Please update with your valuable comments, so that others can use it.