Can I use VARCHAR as the PRIMARY KEY?

前端 未结 4 876
清酒与你
清酒与你 2020-12-01 07:13

I have a table for storing coupons/discounts, and I want to use the coupon_code column as the primary key, which is a VARCHAR.

My rationale is that, eac

4条回答
  •  粉色の甜心
    2020-12-01 07:45

    It depends on the specific use case.

    If your table is static and only has a short list of values (and there is just a small chance that this would change during a lifetime of DB), I would recommend this construction:

    CREATE TABLE Foo 
    (
        FooCode VARCHAR(16), -- short code or shortcut, but with some meaning.
        Name NVARCHAR(128), -- full name of entity, can be used as fallback in case when your localization for some language doesn't exist
        LocalizationCode AS ('Foo.' + FooCode) -- This could be a code for your localization table... 
    )
    

    Of course, when your table is not static at all, using INT as primary key is the best solution.

提交回复
热议问题