DB: To use identity column or not?

前端 未结 4 763
遥遥无期
遥遥无期 2021-02-06 08:33

While designing a table my colleague here says that I should avoid identity column as it is specific to SQL Server and MS Access, But I differ with his views as it makes my codi

4条回答
  •  情深已故
    2021-02-06 09:18

    Do not use identity column unless you're fully aware of its pitfalls and has no valid reason to use SEQUENCE or an emulated sequence generator.

    Sequences are much more flexible and do not have the disadvantages/restrictions that Identity columns have.

    From http://www.jumpingbean.co.za/blogs/mark/identity_autoincrement_fields_and_database_sequences :

    The pain with auto-incrementing

    Copying over data while preserving identity value

    Auto-incrementing keys can become a pain when you need to copy whole tabels and preserve the primary key value. Trying to insert directly into an identity column will result in a error being raised. Typically the vendor provides some statements that allow you to temporarily drop the constraint so you can insert existing values. In MSSQL you can issue the command

    "SET IDENTITY_INSERT products ON".

    Other vendors will require you to drop the constraint and then re-enable it.

    More pain- how to retrieve value of newly inserted rows?

    In addition the server usually provides different ways to retrieve the identity column value for a newly inserted row. For MySQL this is the LAST_INSERT_ID() function and for MSSQL it is @@identity eg select @@identity.

    MS SQL Server 2011 will support SEQUENCE.

    If you use a RDBMS server that doesn't support SEQUENCE (like MSSQL pre-2011 or MySQL), there are two alternatives:

    1. Switch to PostgreSQL. This is the easiest option, really. You get enterprise-grade, fully open source RDBMS server. And you can have commercial support too if you want.
    2. Use a data access library that supports emulating SEQUENCE. JPA 2.0 implementations e.g. EclipseLink, Hibernate make this very trivial for you (TABLE strategy). It's not mutually exclusive with the above. Using JPA 2.0 with PostgreSQL will make your life so much easier than, say, raw JDBC with MySQL.

提交回复
热议问题