I have a simple SELECT statement with a couple columns referenced in the WHERE clause. Normally I do these simple ones in the VB code (setup a Command object, set Command Type to text, set Command Text to the Select statement). However I’m seeing timeout problems. We’ve optimized just about everything we can with our tables, etc.
I’m wondering if there’d be a big performance hit just because I’m doing the query this way, versus creating a simple stored procedure with a couple params. I’m thinking maybe the inline code forces SQL to do extra work compiling, creating query plan, etc. which wouldn’t occur if I used a stored procedure.
An example of the actual SQL being run:
SELECT TOP 1 * FROM MyTable WHERE Field1 = @Field1 ORDER BY ID DESC
A well formed “inline” or “ad-hoc” SQL query – if properly used with parameters – is just as good as a stored procedure.
But this is absolutely crucial: you must use properly parametrized queries! If you don’t – if you concatenate together your SQL for each request – then you don’t benefit from these points…
Just like with a stored procedure, upon first executing, a query execution plan must be found – and then that execution plan is cached in the plan cache – just like with a stored procedure.
That query plan is reused over and over again, if you call your inline parametrized SQL statement multiple times – and the “inline” SQL query plan is subject to the same cache eviction policies as the execution plan of a stored procedure.
Just from that point of view – if you really use properly parametrized queries – there’s no performance benefit for a stored procedure.
Stored procedures have other benefits (like being a “security boundary” etc.), but just raw performance isn’t one of their major plus points.