- --兩種UDF
- --標量函數 返回單個數據值,而且其類型是在return字句中定義的
- create function SUMEmp2(@emp1 int)
- returns int
- AS
- begin
- --聲明變量@emp2count ,存儲總值
- declare @emp2Count int
- select @emp2Count =SUM (emp2)
- from dbo.pp where Emp1=@emp1
- --若是變量爲空,從新賦值0
- if(@emp2Count is null)
- set @emp2Count =0
- print @emp2count
- return @emp2count
- end
- --函數調用
- select VerdorID,dbo.SUMEmp2(emp1) from pp
- --PS :標量函數返回一個單獨的值,一般在列表和where子句中使用
- --標量函數位置
- --查詢中: select 語句中
- -- where 或having 字句中
- -- 做爲 update 中set字句中
- -- T-SQL語句: case表達式中
- -- print 語句中(只適用於字符串函數)
- -- 做爲存儲過程的return 語句(只適用於返回整數的標量函數)
- -- 函數和存儲過程當中:做爲用戶自定義函數的return字句,前提是被調用的用戶函數返回的值可隱式轉換爲進行調用的函數的返回值類型
- ---表值函數
- --表值函數遵照與標量函數相同的規則,區別在於表值函數返回一個表做爲輸出
- ---通常在select 語句的from 字句中進行引用,並能夠與其餘表或視圖進行鏈接
- --內聯表值函數能夠實現參數化視圖的功能
- --視圖的一個侷限性是在建立視圖是,不容許在視圖中包括用戶提供的參數,一般能夠在調用視圖時提供的where字句解決問題
- --建立表值函數
- create function FunctionAA (@emp1 int)
- returns table --return 指定表爲返回的數據類型
- as
- return(
- select A.* from pp A inner join pp B on a.VerdorID=b.VerdorID
- where a.Emp1=@emp1)--select 語句的結果定義了返回變量的格式
- --函數的內容是一個單條的select語句,內聯函數使用的select語句與視圖中使用的select語句,受到一樣的限制
- --該函數的主體不須要包含在begin ..end 中
- --調用
- select * from FunctionAA(4)
- --可在一般使用視圖的任何地方使用內聯表值函數
- --多語句表值函數 是視圖和存儲過程的結合,可以使用返回表的用戶定義函數來代替存儲過程或視圖
- create function functionBB (@sex varchar(20))
- returns @emptable table ---returns 定義表爲返回值類型,並定義告終構(名稱和格式)
- (id int identity(1,1) primary key not null,name varchar(20),class varchar(20))
- AS
- begin --begin...end 界定函數主體
- if(@sex='1')
- begin
- insert into @emptable
- select name,('T'+class) from student3 where sex=1
- --或 select name,('T'+class) from student3 where sex='true'
- end
- else if(@sex='0')
- begin
- insert into @emptable
- select name,('F'+class) from student3 where sex='false'
- --或 select name,('F'+class) from student3 where sex=0
- end
- else
- begin
- insert into @emptable
- select name,('null'+class) from student3 where sex is null
- end
- return
- end
- --調用
- select * from functionBB ('0')
- ---表值函數返回一個表變量,並在from字句使用
- ---肯定性與非肯定性函數
- --對於相同的輸入值函數,每次調用肯定性函數則返回相同的值 如:內置函數cos
- --對於相同的輸入值函數,每次調用非肯定性函數則返回不一樣的值 如:內置函數getdate()
- --一個函數是非肯定性仍是肯定性,決定了是否在該函數結果集上創建索引,以及可否在引用該函數
- --的視圖上定義彙集函數, 若是一個函數是非肯定行的,就不能索引該函數的結果