Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stored Procedures and ORM's

What's the purpose of stored procedures compared to the use of an ORM (nHibernate, EF, etc) to handle some CRUD operations? To call the stored procedure, we're just passing a few parameters and with an ORM we send the entire SQL query, but is it just a matter of performance and security or are there more advantages?

I'm asking this because I've never used stored procedures (I just write all SQL statements with an ORM and execute them), and a customer told me that I'll have to work with stored procedures in my next project, I'm trying to figure out when to use them.

like image 867
Gui Avatar asked Mar 17 '11 23:03

Gui


People also ask

Why ORM is better than stored procedure?

Speed and power of SQL generated by an ORM is just the same as straight T-SQL. (They also get precompiled and reused in SQL Server). It is also easier and faster to write, way less risky, and way more maintainable.

What is difference between store procedure and views?

View is simple showcasing data stored in the database tables whereas a stored procedure is a group of statements that can be executed. A view is faster as it displays data from the tables referenced whereas a store procedure executes sql statements.

What is the difference between store procedure and transaction?

Parameter: Stored Procedures can take parameters as input but Triggers cannot take parameters as input. Return Values: Stored Procedures can return values but Triggers cannot return value. Transaction: Transaction statements such as begin transaction, commit transaction, and rollback inside a Stored Procedure.


1 Answers

Stored Procedures are often written in a dialect of SQL (T-SQL for SQL Server, PL-SQL Oracle, and so on). That's because they add extra capabilities to SQL to make it more powerful. On the other hand, you have a ORM, let say NH that generates SQL.

the SQL statements generated by the ORM doesn't have the same speed or power of writing T-SQL Stored Procedures. Here is where the dilemma enters: Do I need super fast application tied to a SQL Database vendor, hard to maintain or Do I need to be flexible because I need to target to multiple databases and I prefer cutting development time by writing HQL queries than SQL ones?

Stored Procedure are faster than SQL statements because they are pre-compiled in the Database Engine, with execution plans cached. You can't do that in NH, but you have other alternatives, like using Cache Level 1 or 2.

Also, try to do bulk operations with NH. Stored Procedures works very well in those cases. You need to consider that SP talks to the database in a deeper level.

The choice may not be that obvious because all depends of the scenario you are working on.

like image 190
Marcote Avatar answered Sep 23 '22 02:09

Marcote