MySQL stored procedures or php code?

前端 未结 11 723
伪装坚强ぢ
伪装坚强ぢ 2020-12-29 14:35

A general question, without a specific case in mind - is it usually preferred to use MySQL stored procedures over writing a PHP script that performs the same calculations an

11条回答
  •  醉梦人生
    2020-12-29 15:16

    Well, there's a side of this argument that I very rarely hear, so I'll write it here...

    Code is version controlled. Databases are not. So if you have more than one instance of your code, you'll need some way of performing migrations automagically upon update or you'll risk breaking things. And even with that, you still face the problems of "forgetting" to add an updated SP to the migration script, and then breaking a build (potentially without even realizing it if you aren't testing REALLY idepth).

    From debugging and maintenance, I find SP's 100x as hard to dissect as raw SQL. The reason is that it requires at least three steps. First, look in PHP code to see what code is called. Then go into database and find that procedure. Then finally look at the procedure's code.

    Another argument (along the lines of version control), is there's no svn st command for the SP's. So if you get a developer who manually modifies a SP, you're going to have a hell of a time figuring that out (assuming they are not all managed by a single DBA).

    Where SP's really shine is when you have multiple applications talking to the same database schema. Then, you only have one place where DDL and DML is stored, and both applications can share it without having to add a cross dependency in one or more libraries.

    So, in short, my view is as follows:

    Use Stored Procedures:

    1. When you have multiple applications working off the same dataset
    2. When you have the need to loop over queries and execute other queries (avoiding the TCP layer losses can GREATLY improve efficiency)
    3. When you have a really good DBA, as it will enforce all SQL being handled by him/her.

    Use raw SQL/ORM/Generated SQL just about in any other case (Just about, since there are bound to be edge cases I am not thinking about)...

    Again, that's just my $0.02...

提交回复
热议问题