Are there any patterns for writing stored procs? like:
Any good article or book to read about these patterns...
thanks
Typically, stored procs follow a CRUD (http://en.wikipedia.org/wiki/Create,_read,_update_and_delete) pattern, but they don't have to be limited to this.
1) You probably want to combine update and insert. If the primary key is filled then it's an update, otherwise it's an insert. For GUID's and other client-generated keys, you update first, and if the rowcount is zero, you need to do an insert. The insert/update proc typically returns a primary key.
You're going to want a get_by_id proc as well as some number of get_by_non-unique-criteria, which return any number of rows. The idea is to make sure the columns in the result set are identical in all of the get/list procs.
The target of these procedures isn't necessarily one table, or even one view, but rather a logical entity, so you may need to do various joins, both for relationships and lookups. It may help to return multiple result sets.
2) Views are handy, but not particularly relevant to this. Sometimes they help with reuse, but not always.
3) It all depends on the business rules. You can certainly prevent certain kinds of data corruption at the stored proc level, but there are limits to how much it can or should know. Having said that, there are special-purpose cases where you might want to put more logic in the proc, such as login.
4) You can't always do so, but you can sometimes factor out common code into lower-level stord procs that the user doesn't call.
Hope this is a start.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With