When should I use stored procedures?

前端 未结 19 2555
眼角桃花
眼角桃花 2020-12-04 10:53

When should I be using stored procedures instead of just writing the logic directly in my application? I\'d like to reap the benefits of stored procedures, but I\'d also lik

19条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-04 11:38

    I'd argue that you should avoid stored procedures.

    Why might we avoid it?

    • To avoid tight-coupling between applications and databases. If we use stored procedures, we won't be able to easily change our underlying database in the future because we'd have to either:

      1. Migrate stored procedures from one database (e.g. DB2) to another (e.g. SQL Server) which could be painstakingly time-consuming or...
      2. Migrate all the queries to the applications themselves (or potentially in a shared library)
    • Because code-first is a thing. There a several ORMs which can enable us to target any database and even manage the table schemas without ever needing to touch the database. ORMs such as Entity Framework or Dapper allow developers to focus on building features instead of writing stored procedures and wiring them up in the application.

    • It's yet another thing that developers need to learn in order to be productive. Instead, they can write the queries as part of the applications which makes the queries far simpler to understand, maintain, and modify by the developers who are building new features and/or fixing bugs.

    I know of a company which was heavily reliant on stored procedures. As the number of microservices grew and as the original database-oriented developers left, the company was left with a black box that no one was allowed to touch for fear that it would take everything down. Now that they want to move to a different database and move to the cloud, it's much more difficult than it needs to be and they are moving the stored procedure logic into their applications anyways.

提交回复
热议问题