sql server: generate primary key based on counter and another column value

后端 未结 2 1357
北恋
北恋 2020-12-21 15:32

I am creating a customer table with a parent table that is company. It has been dictated(chagrin) that I shall create a primary key for the customer table that is a combinat

2条回答
  •  情深已故
    2020-12-21 15:52

    As others said before me, using a primary key with calculated auto-increment values sounds like a very bad idea!

    If you are allowed to and if you can live with the downsides (see at the bottom), I would suggest the following:

    Use a normal numeric auto-increment key and a char(4) column which only contains the company id.
    Then, when you select from the table, you use row_number on the auto-increment column and combine that with the company id so that you have an additional column with a "key" that looks like you wanted (MSFT00001, MSFT00002, ...)

    Example 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 on it:

    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 additional 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 could create a view with this query and let everyone use that view, to make sure everyone sees the "special key" column.

    However, this solution has two downsides:

    1. You need at least SQL Server 2005 in order for row_number to work.
    2. The numbers in the special key will change when you delete companies from the table. So, if you don't want the numbers to change, you have to make sure that nothing is ever deleted from that table.

提交回复
热议问题