As others have said, using a primary key with calculated auto-increment values sounds like a very bad idea!
If you are allowed, and if you can live with minuses (see below), I would suggest the following:
Use a regular numeric key for automatic increment and a column char (4), which contains only the company identifier.
Then, when you select from the table, you use row_number in the auto-increment column and combine this with the company identifier so that you have an additional column with a “key” that looks the way you like (MSFT00001, MSFT00002, ...)
Sample data:
create table customers ( Id int identity(1,1) not null, Company char(4) not null, CustomerName varchar(50) not null ) insert into customers (Company, CustomerName) values ('MSFT','First MSFT customer') insert into customers (Company, CustomerName) values ('MSFT','Second MSFT customer') insert into customers (Company, CustomerName) values ('ABCD','First ABCD customer') insert into customers (Company, CustomerName) values ('MSFT','Third MSFT customer') insert into customers (Company, CustomerName) values ('ABCD','Second ABCD customer')
This will create a table that looks like this:
Id Company CustomerName ------------------------------------ 1 MSFT First MSFT customer 2 MSFT Second MSFT customer 3 ABCD First ABCD customer 4 MSFT Third MSFT customer 5 ABCD Second ABCD customer
Now run the following query:
select Company + right('00000' + cast(ROW_NUMBER() over (partition by Company order by Id) as varchar(5)),5) as SpecialKey, * from customers
This returns the same table, but with an extra column with your "special key":
SpecialKey Id Company CustomerName --------------------------------------------- ABCD00001 3 ABCD First ABCD customer ABCD00002 5 ABCD Second ABCD customer MSFT00001 1 MSFT First MSFT customer MSFT00002 2 MSFT Second MSFT customer MSFT00003 4 MSFT Third MSFT customer
You can create a view with this query and let everyone use this view to make sure everyone sees the "special key" column.
However, this solution has two drawbacks:
- You need at least SQL Server 2005 to order
row_number to work. - The numbers in the special key will change when companies are removed from the table. Thus, if you do not want the numbers to change, you must make sure that nothing is ever deleted from this table.