除了在我們常用的程序開發中要用到函數外,在sql語句中也常用到函數,不論哪種,思想都沒有變,都是為了封裝,可復用。
創建的方法和整體結構都大體相同,都少不了函數名,函數的形參,返回值等這些。
一、表值函數
從名字可知,表值函數,是將表作為值進行返回的函數。請看本人項目中的一個表值函數:
USE [cnpc] GO /****** Object: UserDefinedFunction [dbo].[FUN_EaScoreDetail] Script Date: 2019/7/1 星期一 下午 3:50:49 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: <Author,,zhengwei> -- Create date: <Create Date,20190624,> -- Description: <Description,立項考核明細表,給立項考核統計提供最基本的數據,很多地方會用到這個函數,不要輕易修改,> -- ============================================= CREATE FUNCTION [dbo].[FUN_EaScoreDetail] (@unitcode nvarchar(50),@startdate datetime,@enddate datetime) RETURNS @scoreResult TABLE ( EaId int, Createdtime datetime, ApplyUnitCode nvarchar(50), updateG int, ReturnG int, AdjustG int, TerminatedG int, Score float ) AS BEGIN insert into @scoreResult select s.EaId EaId,min(e.createdtime) Createdtime,e.unit_code ApplyUnitCode, sum(case ScoreType when 'Upload' then 1 else 0 end) as updateG, sum(case ScoreType when 'Reply' then 1 else 0 end) as ReturnG, sum(case ScoreType when 'Adjust' then 1 else 0 end) as AdjustG, sum(case ScoreType when 'Terminated' then 1 else 0 end) as TerminatedG, (case min(s.IncreaseOrReduceScore) when 1 then 1 else (1+min(s.IncreaseOrReduceScore)) end) as Score from EaScoreDetail s inner join Ea e on e.id=s.EaId inner join unitinfo u on e.unit_code = u.dm where e.createdtime BETWEEN @startdate and @enddate and e.unit_code like @unitcode+'%' group by s.EaId,e.unit_code RETURN END
表值函數的返回結果為一個表,那么首先就是要創建一個表@scoreResult ,並聲明了表中一些字段的,最后將查詢的結果插入這個表中,注意,插入結果中select后面字段的順序要與聲明表進字段的順序相同。
二、標量值函數
從名字可知,表值函數,是將一個值進行返回的函數。請看本人項目中的一個標量值函數:
USE [cnpc] GO /****** Object: UserDefinedFunction [dbo].[FUN_getPassportQualityScore] Script Date: 2019/7/1 星期一 下午 3:58:50 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO Create function [dbo].[FUN_getPassportQualityScore] ( @approvalCount float, @successApprovalCount float, @borrowCount float, @overtimeUnReturnCount float, @unBorrowVisaCount float, @unBorrowForTK float ) returns nvarchar(100) as begin declare @passportQualityScore float, @collectionRate float, @legalRate float, @passRate float set @collectionRate=0 set @legalRate =0 set @passRate =0 ---- 收繳率 if(@borrowCount>0) set @collectionRate = 1- @overtimeUnReturnCount/@borrowCount ---- 合規借出率 if((@unBorrowVisaCount+@unBorrowForTK+@borrowCount)>0) set @legalRate = @borrowCount/(@unBorrowVisaCount+@unBorrowForTK+@borrowCount) ---- 一次辦理合格率 if(@approvalCount>0) set @passRate = @successApprovalCount/@approvalCount ----質量總分(也就是最終要返回的結果) set @passportQualityScore = (@collectionRate + @legalRate+@passRate)/0.03 return round(@passportQualityScore,2) end
標量值函數返回的值為一個數字,也就是將傳入的參數通過計算得到一個結果。
三、表值函數與標量值函數的使用
1、在存儲過程中使用表值函數與使用數據庫中的表是一樣的。直接調用並傳入需要的參數就可,如下:
2、在存儲過程中使用標量值函數正如程序中使用方法一下,傳入指定的參數就可,如圖中的標量值函數是用select中每列的值作為參數進行調用的。


有需要微信投票的朋友可以找我,WX:18963948278