这两天一直在研究一个问题,所以对sql中dynamic sql 做了部分了解,不过最终都归结到存储过程和函数的区别这个问题上。
本质上没区别。只是函数只能返回一个变量的限制;而存储过程可以返回多个。函数是可以嵌入在sql中使用的,可以在select中调用,而存储过程不行。函数限制比较多,如不能用临时表,只能用表变量等,而存储过程的限制相对就比较少。
1. 一般来说,存储过程实现的功能要复杂一点,而函数的实现的功能针对性比较强。
2. 当对数据库进行复杂操作时(如对多个表进行Update、Insert、Query、Delete时),可将此复杂操作用存储过程封装起来与数据库提供的事务处理结合一起使用。存储过程可以从自己的存储过程内引用其它存储过程,这可以简化一系列复杂语句.
3. 存储过程一般是作为一个独立的部分来执行,而函数可以作为查询语句的一个部分来调用,由于函数可以返回一个表对象,因此它可以在查询语句中位于FROM关键字的后面。
4. 存储过程只在创造时进行编译,以后每次执行存储过程都不需再重新编译,而一般SQL语句每执行一次就编译一次,所以使用存储过程可提高数据库执行速度。
5. 存储过程可以接受参数、输出参数、返回单个或多个结果集以及返回值,可以向程序返回错误原因。但函数只能返回一个特定类型的值或者表对象。
6. 存储过程中的CRUD的操作会影响数据库状态,但函数却不能。
存储过程:可以使得对的管理、以及显示关于及其用户信息的工作容易得多。存储过程是SQL语句和可选控制流语句的预编译集合,以一个名称存储并作为一个单元处理。存储过程存储在数据库内,可由应用程序通过一个调用执行,而且允许用户声明变量、有条件执行以及其它强大的编程功能。存储过程可包含程序流、逻辑以及对数据库的查询。它们可以接受参数、输出参数、返回单个或多个结果集以及返回值。
函数:是由一个或多个SQL语句组成的子程序,可用于封装代码以便重新使用。自定义函数诸多限制,有许多语句不能使用,许多功能不能实现。函数可以直接引用返回值,用表变量返回记录集。但是,用户定义函数不能用于执行一组修改全局数据库状态的操作。函数有三种不同的类型:
Scalar-valued function - returns a scalar value such as an integer or a timestamp. Can be used as column name in queries
Inline function - can contain a single SELECT statement.
Table-valued function - can contain any number of statements that populate the table variable to be returned. They become handy when you need to return a set of rows, but you can't enclose the logic for getting this rowset in a single SELECT statement.
两者声明的区别
存储过程和函数的具体操作可参考:mysql中存储过程的基本操作和mysql中函数应用实例。
存储过程:
1: CREATE OR REPLACE PROCEDURE my_proc
2: (p_name IN VARCHAR2 := 'John') as begin ... end
3:
函数:
1: CREATE OR REPLACE FUNCTION my_func
2: (p_name IN VARCHAR2 := 'John') return varchar2 as begin ... end
应用的区别
一般情况下,尽量避免使用table valued函数,因为会造成一定的性能影响。下面摘抄自stackoverflow:
应用的区别
一般情况下,尽量避免使用table valued函数,因为会造成一定的性能影响。下面摘抄自stackoverflow:
SQL Server functions, like cursors, are meant to be used as your last weapon! They do have performance issues and therefore using a table-valued function should be avoided as much as possible. Talking about performance is talking about a table with more than 1,000,000 records hosted on a server on a middle-class hardware; otherwise you don't need to worry about the performance hit caused by the functions.
Never use a function to return a result-set to an external code (like ADO.Net)
Use views/stored procs combination as much as possible. you can recover from future grow-performance issues using the suggestions DTA (Database Tuning Adviser) would give you (like indexed views and statistics) --sometimes!
for further reference see: http://databases.aspfaq.com/database/should-i-use-a-view-a-stored-procedure-or-a-user-defined-function.html
参考资料: 1、mysql中存储过程的基本操作
2、mysql中函数应用实例
3、SQL一个存储过程调用另一个存储过程 获得返回值问题
4、Difference between Stored procedures and functions