Custom PrimaryKey Generation with autoincrement

后端 未结 6 833
小蘑菇
小蘑菇 2021-01-22 21:08

I need to define and generate primary key for 2 or more tables.

Tables hold same type of data but FOR Some BUSINESS RULES we have to make them separate say like

6条回答
  •  长发绾君心
    2021-01-22 21:12

    You can definitely do this with a computed column.

    Either, if you stick with your two tables, you could just simply add a single computed, persisted column like this:

    ALTER TABLE Local_Customer
      ADD CustomerID AS 'LOC' + CAST(ID AS VARCHAR(7)) PERSISTED
    
    ALTER TABLE International_Customer
      ADD CustomerID AS 'INT' + CAST(ID AS VARCHAR(7)) PERSISTED
    

    If you decide to have a single table with a discrimator column, e.g. "IsDomestic" of type BIT, you could do a single computed column that will use "LOC" or "INT" as prefix, based on the value of the "IsDomestic" column:

    ALTER TABLE Customer
      ADD CustomerID AS CASE IsDomestic WHEN 0 THEN 'INT' ELSE 'LOC' END + CAST(ID AS VARCHAR(7)) PERSISTED
    

    Either way - your "ID" field of type INT IDENTITY will be automatically increased for each row, and the computed column will create a more human-readable "CustomerID" automagically, without any further effort on your part.

提交回复
热议问题