sql server中函數分別有:表值函數、標量函數、聚合函數、系統函數。這些函數中除系統函數外其他函數都需要用戶進行自定義。 一、表值函數 簡單表值函數 創建 create function fu_selectUser 創建 create function fu_selectUser ( ( ) ...
sql server中函數分別有:表值函數、標量函數、聚合函數、系統函數。這些函數中除系統函數外其他函數都需要用戶進行自定義。
一、表值函數
簡單表值函數
創建 create function fu_selectUser ( ) returns table --表值函數返回類型為table as return( select * from user ) 調用 select * from fu_selectUser() --由於該函數是表值函數,所以可以當成表進行應用 --結果由select語句來決定反回結果 結構create function fu_name
(參數)
return table
as
return
(--函數體)
end 複雜表值函數-多語句表值函數 多語句表值函數需要指定具體的table類型的結構。可以自己定義哪些欄位返回,所以可以支持多條語句執行來創建Table數據 創建: 多語句表值函數 create function fu_cu1( )returns @user table--指定表名 該表為虛擬表不存在 (--指定欄位 id int, name varchar(20), age int ) as begin insert into @user values (20120101,'小明',12) insert into @user values (20120105,'小紅',12) insert into @user values (select id,name,age from user2) return end 結構 create function fu_name (--參數) returns @tablename table --指定表名 (--指定欄位) as begin --函數體 return end 二、標值函數 創建 create function fu_Sum ( @value1 int ,@value2 int )returns int as begin declare @sum int --聲明變數 select @sum = @value1 + @value2 return @sum end 調用 select dbo.fu_Sum(45,55)
![](https://images2018.cnblogs.com/blog/829317/201809/829317-20180909142610898-1175264242.png)