1. --两种UDF  
  2.  
  3.  
  4. --标量函数  返回单个数据值,并且其类型是在return字句中定义的  
  5. create function SUMEmp2(@emp1 int)  
  6. returns  int   
  7. AS   
  8. begin  
  9. --声明变量@emp2count ,存储总值  
  10. declare @emp2Count int  
  11. select @emp2Count =SUM (emp2)  
  12. from dbo.pp where Emp1=@emp1  
  13. --如果变量为空,重新赋值0  
  14. if(@emp2Count is null)  
  15. set @emp2Count =0 
  16. print @emp2count  
  17. return @emp2count  
  18. end  
  19.  
  20. --函数调用  
  21. select VerdorID,dbo.SUMEmp2(emp1) from pp  
  22.    
  23.  --PS :标量函数返回一个单独的值,通常在列表和where子句中使用  
  24.  --标量函数位置  
  25.    
  26.  --查询中: select 语句中  
  27.  -- where 或having 字句中  
  28.  -- 作为 update 中set字句中  
  29.    
  30.  -- T-SQL语句: case表达式中  
  31.  -- print 语句中(只适用于字符串函数)  
  32.  -- 作为存储过程的return 语句(只适用于返回整数的标量函数)  
  33.     
  34.  -- 函数和存储过程中:作为用户自定义函数的return字句,前提是被调用的用户函数返回的值可隐式转换为进行调用的函数的返回值类型  
  35.    
  36.    
  37.    
  38.    
  39.    
  40.    
  41.  ---表值函数  
  42.  --表值函数遵守与标量函数相同的规则,区别在于表值函数返回一个表作为输出  
  43.  ---一般在select 语句的from 字句中进行引用,并可以与其他表或视图进行连接  
  44.    
  45.  
  46.  --内联表值函数可以实现参数化视图的功能  
  47.  --视图的一个局限性是在创建视图是,不允许在视图中包括用户提供的参数,通常可以在调用视图时提供的where字句解决问题  
  48.  --创建表值函数  
  49.  create function FunctionAA (@emp1 int)  
  50.  returns table  --return 指定表为返回的数据类型  
  51.  as   
  52.  return(  
  53.  select A.* from pp A inner join pp B on a.VerdorID=b.VerdorID   
  54.  where a.Emp1=@emp1)--select 语句的结果定义了返回变量的格式  
  55.    
  56.  --函数的内容是一个单条的select语句,内联函数使用的select语句与视图中使用的select语句,受到同样的限制  
  57.  --该函数的主体不需要包含在begin ..end 中  
  58.  --调用   
  59.  select * from FunctionAA(4)   
  60.    
  61.  --可在通常使用视图的任何地方使用内联表值函数  
  62.    
  63.    
  64.    
  65.  
  66.  --多语句表值函数 是视图和存储过程的结合,可使用返回表的用户定义函数来代替存储过程或视图  
  67.  create function functionBB (@sex varchar(20))  
  68.  returns @emptable table  ---returns 定义表为返回值类型,并定义了结构(名称和格式)  
  69.  (id int identity(1,1) primary key not null,name varchar(20),class varchar(20))  
  70.  AS  
  71.  begin --begin...end 界定函数主体  
  72.   if(@sex='1')  
  73.   begin  
  74.   insert into @emptable  
  75.   select name,('T'+class) from student3 where sex=1   
  76.   --或 select name,('T'+class) from student3 where sex='true' 
  77.   end   
  78.   else if(@sex='0')  
  79.   begin   
  80.   insert into @emptable  
  81.   select name,('F'+class) from student3 where sex='false' 
  82.   --或 select name,('F'+class) from student3 where sex=0 
  83.   end   
  84.   else  
  85.   begin  
  86.   insert into @emptable  
  87.   select name,('null'+class) from student3 where sex is null  
  88.   end  
  89.  return   
  90.  end  
  91.    
  92.  --调用  
  93.  select * from functionBB ('0')  
  94.     
  95.   ---表值函数返回一个表变量,并在from字句使用  
  96.    
  97.  
  98.  
  99. ---确定性与非确定性函数  
  100. --对于相同的输入值函数,每次调用确定性函数则返回相同的值 如:内置函数cos  
  101. --对于相同的输入值函数,每次调用非确定性函数则返回不同的值 如:内置函数getdate()  
  102. --一个函数是非确定性还是确定性,决定了是否在该函数结果集上建立索引,以及能否在引用该函数  
  103. --的视图上定义聚集函数, 如果一个函数是非确定行的,就不能索引该函数的结果