sqlserver 表值函數與標量值函數

除了在咱們經常使用的程序開發中要用到函數外,在sql語句中也經常使用到函數,不論哪一種,思想都沒有變,都是爲了封裝,可複用。sql

建立的方法和總體結構都大致相同,都少不了函數名,函數的形參,返回值等這些。數據庫

1、表值函數app

從名字可知,表值函數,是將表做爲值進行返回的函數。請看本人項目中的一個表值函數:函數

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後面字段的順序要與聲明表進字段的順序相同。
2、標量值函數spa

從名字可知,表值函數,是將一個值進行返回的函數。請看本人項目中的一個標量值函數:code

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

標量值函數返回的值爲一個數字,也就是將傳入的參數經過計算獲得一個結果。blog

3、表值函數與標量值函數的使用ip

一、在存儲過程當中使用表值函數與使用數據庫中的表是同樣的。直接調用並傳入須要的參數就可,以下:開發

二、在存儲過程當中使用標量值函數正如程序中使用方法一下,傳入指定的參數就可,如圖中的標量值函數是用select中每列的值做爲參數進行調用的。
相關文章
相關標籤/搜索