定义
对于SQL Server来讲,我们声明一个变量的方式是用@变量名,而且相对于编程来讲,SQL Server声明的方式跟我们开了个玩笑,是先变量后面才是类型。对于需要传参跟不需要传参的方式,其实跟我们编程的方式一样。有参数则是如下方式:
CREATE FUNCTION GetSum( @firstNum int, @secondNum int )
如果没有参数,则只要保留括号即可。跟我们理解的函数写法一致。
CREATE FUNCTION GetSum()
标量函数
所谓标量函数简单点来讲就是返回的结果只是一个标量,对于我来讲,返回的结果就是一种类型的一个值。
写法如下:CREATE FUNCTION( -- Add the parameters for the function here <@Param1, sysname, @p1> ) RETURNS AS BEGIN -- Declare the return variable here DECLARE <@ResultVar, sysname, @Result> -- Add the T-SQL statements to compute the return value here SELECT <@ResultVar, sysname, @Result> = <@Param1, sysname, @p1> -- Return the result of the function RETURN <@ResultVar, sysname, @Result> END
例子:
CREATE FUNCTION GetSum( @firstNum int, @secondNum int ) RETURNS int AS BEGIN -- Declare the return variable here DECLARE @result int -- Add the T-SQL statements to compute the return value here SELECT @result=@firstNum+@secondNum -- Return the result of the function RETURN @result END GO
内联表值函数
内联表值函数返回的是表数据,表数据就是Table类型。
写法如下:CREATE FUNCTION( -- Add the parameters for the function here <@param1, sysname, @p1> , <@param2, sysname, @p2> ) RETURNS TABLE AS RETURN ( -- Add the SELECT statement with parameter references here SELECT 0 ) GO
例子:
CREATE FUNCTION selectTeacherTest( @Name varchar(20) ) RETURNS TABLE AS RETURN ( select * from Teacher where Teacher.Name=@Name ) GO
调用: 必须从返回表里面进行“查询”
select * from selectTeacherTest('刘英')
多语句表值函数
多语句表值函数跟内联表值函数都是表值函数,它们返回的结果都是Table类型。多语句表值函数顾名思义,就是可以通过多条语句来创建Table类型的数据。这里不同于内联表值函数,内联表值函数的返回结果是由函数体内的SELECT语句来决定。而多语句表值函数,则是需要指定具体的Table类型的结构。也就是说返回的Table,已经定义好要哪些字段返回。所以它能够支持多条语句的执行来创建Table数据。
写法如下:-- =============================================-- Author:-- Create date: -- Description: -- ============================================= CREATE FUNCTION ( -- Add the parameters for the function here <@param1, sysname, @p1> , <@param2, sysname, @p2> ) RETURNS <@Table_Variable_Name, sysname, @Table_Var> TABLE ( -- Add the column definitions for the TABLE variable here , ) AS BEGIN -- Fill the table variable with the rows for your result set RETURN END GO
例子:
-- =============================================-- Author:-- Create date: -- Description: -- ============================================= ALTER FUNCTION DemoFun ( ) RETURNS @result TABLE ( name nvarchar(20), city nvarchar(20), age int, salary int ) AS BEGIN -- Fill the table variable with the rows for your result set insert into @result(name, city, age, salary) select FName,FCity,FAge,FSalary from dbo.T_Person where FSalary>8000 insert into @result(name, city, age, salary) values ('测试','China', 1, 0) RETURN END GO
其他
可以看得出,多语句表值函数的返回结果是定义好表结构的虚拟表。这又跟标量函数一样了吧,只不过标量函数是返回一种类型的标量值而已。而且在多语句表值函数里面,你也会发现最后一句是RETURN。告诉执行程序,多语句表值函数已经执行完成。函数体结构跟标量函数的结构一样。对于类型放在变量后面这种方式确实需要好好转换一下观念。
RETURNS <@Table_Variable_Name, sysname, @Table_Var> TABLE ( -- Add the column definitions for the TABLE variable here, )
参考: