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

user347755 picture user347755 · May 24, 2010 · Viewed 35.8k times · Source

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

Answer

TT. picture TT. · Sep 2, 2017

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.