Interview question - when to use stored procs

Camillia
Camillia used Ask the Experts™
on
I've been ask this question in two different interviews...

What is the benefit of using stored proc ? another guy asked... when would you use a stored proc over inline sql

My answer:
Stored proc makes an application database agnostic ... application layer is separate from the data
Stored procs are compiled

----
When do we want to use a SP over inline SQL?  I didn't answer this one.

---
No matter how much I prepare for an interview... there's always something unexpected thrown at me!
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
I'd say that's generally a good answer for the benefits. As far as WHEN to use an SP over inline SQL, my personal answer would just be "when the inline SQL becomes overly complex or when there's a lot of back-and-forth between server and client."

For example, let's say your application queries some data, then takes that data and performs some basic processing on it and uses the results to perform some additional queries, and then there are some looping sub-queries, etc... This could potentially lead to a half-dozen/dozen queries where the request is sent from the client code to the server, then it processes the response, handles the logic, and kicks off the additional queries, etc... Each one of those can lead to an accumulation of undesirable overhead.

Think of it as trying to bake a cake and you make a separate trip to the supermarket for each ingredient. Even if the supermarket is next door, it still ends up taking up connection resources and time to go make that trip.

An SP, meanwhile, runs all that stuff all within the same DB/server-side process, so there's less overhead and it can respond faster to the results. So it's more like making one trip to the bakery that's inside the supermarket, and then buying the cake from them. That bakery has all the ingredients right there, and they can whip it up quickly and hand you the finished result. You don't have to worry about screwing up the recipe or anything - it's fast and convenient.
thanks for taking the time to answer in detail. I really appreciate it.
AndyAinscowFreelance programmer / Consultant
Commented:
I've done things where the info is presented to the user in a grid with the possibility to sort and/or filter on each column.
For that I have a basic SP to get the relevant data and then use inline SQL to add the final sort/filter based on the user options.
Kyle AbrahamsSenior .Net Developer
Commented:
Inline SQL Vs Stored Procs

If the SQL is going to be used in more than one place or application  or if it needs to be saved for later.
Thanks, Kyle

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial