1. 程式人生 > >SQL自定義函數function

SQL自定義函數function

sql 函數

https://blog.csdn.net/qq_23833037/article/details/53170789


https://www.cnblogs.com/youring2/p/4916400.html


用戶定義自定義函數像內置函數一樣返回標量值,也可以將結果集用表格變量返回
sql函數必須有返回值。

ps: 函數看成一個處理某些數據的功能,因有返回值,則在代碼使用中,需要一個處理過的數據。
可直接調用函數處理數據,返回數據給代碼使用。

標量函數:返回一個標量值。
表格值函數{內聯表格值函數、多表格值函數}:返回行集(即返回多個值)

標量函數和表格值函數的區別在於 返回是標量值(單個數字或者單個數據),還是表格值(多個數據)

1、標量函數

create funetion 函數名(參數) 
return 返回值數據類型 
[with {Encryption | Schemabinding }] 
[as] 
begin 
SQL語句(必須有return 變量或值) 
End

--Schemabinding :將函數綁定到它引用的對象上(註:函數一旦綁定,則不能刪除、修改,除非刪除綁定)

測試數據:


USE [Scratch]
GO
/****** Object:  Table [dbo].[number]    Script Date: 04/19/2018 17:01:31 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[number](
 [number] [int] NULL,
 [name] [nchar](10) NULL
) ON [PRIMARY]
GO

插入數據:

  INSERT INTO number(number,name)
  VALUES(123,'a'),
  (222,'b'),
  (333,'c'),
  (323,'d')

例子:

alter function SumRes(@sco nvarchar(20)) --函數名和參數
returns real --返回real 值類型
-- real=float(24)   
as
begin
declare @sum real 
declare @code varchar(11)
set @code = @sco + '%'
select @sum = sum(number) from number where name like @code
return @sum --返回值
end

引用自定義函數:

用戶自定義函數返回值可放在局部變量中,用set select exec 賦值)

declare @sum1 real,@sum2 real,@sum3 real
set @sum1 = dbo.SumRes('b')
select @sum2 = dbo.SumRes('b')
exec @sum3 = dbo.sumRes'b'
select @sum1 ,@sum2 ,@sum3

技術分享圖片


實例2:

下面的這個函數根據生日返回年齡:

create function dbo.calcAge(@birthday datetime)    --函數名和參數
returns int    --返回值類型
as
begin
    declare @now datetime
    declare @age int
    set @now=getdate()

    set @age=YEAR(@now)-YEAR(@birthday)

    return @age    --返回值
end
print dbo.calcAge('2000-1-1')

執行這段腳本創建函數,創建成功之後,我們調用一下看看效果: 輸出:15


2、表格值函數

a、內聯表格值函數
格式:
create function 函數名(參數)
returns table
[with{ Encryption | Schemabinding }]
as
return(一條SQL語句)

例子:

create function tabcmess(@code nvarchar(50))
returns table
as
return(select * from number where name = @code)

調用和結果:

技術分享圖片

b、多句表格值函數

多表格值函數的定義:包含多條SQL語句,必須或者至少有一條給表格變量賦值!!!

表格變量格式:
returns @變量名(dt) table( 列定義 | 約束定義 )

對表格變量中可以執行 select, insert, update, delete,
但select into 和 insert 語句的結果集是從存儲過程插入。

格式:
create function 函數名(參數)
return @dt table(列的定義)
[with{Encryption | Schemabinding}]
as
begin
SQL語句
end

例子:

create function tabcmess_mul(@code nvarchar(50))
returns @dt table(number int,name nchar(10))
as
begin
insert into @dt select number,name from number where name = @code
return
end

調用和結果:

技術分享圖片


3. 修改自定義函數

alter function tabcmess_mul(@code nvarchar(50))
returns @dt table(number int,name nchar(10))
as
begin
insert into @dt select number,name from number where name = @code
return
end

4. 刪除自定義函數

drop function tabcmess_mul


SQL自定義函數function