Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can we not execute a stored procedure inside a function in SQL Server

Why can we not execute a stored procedure inside a function when the opposite is possible?

like image 961
user347755 Avatar asked May 24 '10 11:05

user347755


2 Answers

You cannot execute a stored procedure inside a function, because a function is not allowed to modify database state, and stored procedures are allowed to modify database state.

This is by definition (see CREATE FUNCTION - Limitations and Restrictions).

User-defined functions cannot be used to perform actions that modify the database state.

A stored procedure might modify database state, or it might not. But the SQL Server compiler shouldn't have to analyze the stored procedure to know whether or not it modifies database state. Therefore, it is not allowed to execute a stored procedure from within a function.

Functions exist to simply calculate something, a value or a table result, nothing more than that. These functions can be called within a SELECT query for instance, e.g.

SELECT calculate_something(a) FROM some_table;

Now consider what would happen if the function calculate_something were allowed to execute a stored procedure which would delete all rows in some_table. Your intention is to calculate something using the value of the some_table.a columns, but you end up... deleting all rows in some_table. That is clearly not something you want to happen.

like image 133
TT. Avatar answered Sep 21 '22 23:09

TT.


I know this is already been answered but in SQL server the function is not suppose to change the data but the procedure is meant to.

In addition to this i like to add that we cannot select a procedure or put it in a where clause but we can do this with a function.

We use function to shorten the code so its greatly helpful as it reduces a lot of query for the coder.

Hope this helps.

like image 41
AtomicFlee Avatar answered Sep 20 '22 23:09

AtomicFlee