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

前端 未结 7 1522
情话喂你
情话喂你 2020-12-17 02:23

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

7条回答
  •  攒了一身酷
    2020-12-17 02:52

    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.

提交回复
热议问题