Should I design a table with a primary key of varchar or int?

后端 未结 13 1114
清酒与你
清酒与你 2020-11-27 13:45

I know this is subjective, but I\'d like to know peoples opinions and hopefully some best practices that I can apply when designing sql server table structures.

I pe

13条回答
  •  醉梦人生
    2020-11-27 14:26

    If Joe Celko was on here, he would have some harsh words... ;-)

    I want to point out that INTs as a hard and fast rule aren't always appropriate. Say you have a vehicle table with all types of cars trucks, etc. Now say you had a VehicleType table. If you wanted to get all trucks you might do this (with an INT identity seed):

    SELECT V.Make, V.Model
    FROM Vehicle as V
    INNER JOIN VehicleType as VT
    ON V.VehicleTypeID = VT.VehicleTypeID
    WHERE VT.VehicleTypeName = 'Truck'
    

    Now, with a Varchar PK on VehicleType:

    SELECT Make, Model
    FROM Vehicle 
    WHERE VehicleTypeName = 'Truck'
    

    The code is a little cleaner and you avoid a join. Perhaps the join isn't the end of the world, but if you only have one tool in your toolbox, you're missing some opportunities for performance gains and cleaner schemas.

    Just a thought. :-)

提交回复
热议问题