백엔드/SQL
[SQL] User-defined Function (3)
leejiwoo21
2021. 12. 4. 00:25
User-defined Function (3)
Table-Valued Function은 inline Table-Valued Function과 Multistatement Table-Valued Function으로 나눌 수 있습니다.
inlined Table-Valued Function과 Multistatement Table-Valued Function의 차이점은 반환값에 차이가 있습니다.
Multistatement Table-Valued Function은 반환할 테이블을 함수 안에서 만들고,
inlined Table-Valued Function은 select문을 사용합니다.
inline Table-Valued Function 문법
CREATE FUNCTION [스키마이름.] 함수이름
([ @인자이름 [AS] [타입의스키마이름] 인자타입
[= default] [ READONLY ]}
[,...n])
RETURNS TABLE -- returns(o), return(x)
[WITH <function_options> [,...n]]
[AS]
RETURN [(] 반환할SELECT문 [)]
[;]
생성 예시
use DreamHome
if object_id('inlineExample') is not null
drop function dbo.inlineExample
go
create function inlineExample()
returns table
return select *from dbo.Branch
go
select * from inlineExample()
출력
dreamhome은 제가 사용한 데이터베이스 이름이고
branch테이블은 제가 사용한 테이블이름입니다.
Multistatement Table-Valued Function 문법
CREATE FUNCTION [ 스키마이름. ] 함수이름
([{ @인자이름 [AS] [ 스키마타입이름. ] 인자타입
[= default ] [ READONLY ] }
[ ,...n ]
]
)
RETURNS @반환할 테이블 변수 <table_type_definition>
[WITH ,fuction_option> [ ,...n ]]
[AS]
BEGIN
function_body
RETURN
END
[;]
생성 예시
use DreamHome
if object_id('daysBetween') is not null
drop function daysBetween
go
create function daysBetween(@sdate as date, @edate as date)
returns @days table(id int, dd date)
as
begin
declare @i int = 1
while(@sdate <= @edate)
begin
insert into @days values(@i,@sdate) -- 반환할 테이블에 추가
set @sdate = dateadd(day,1,@sdate)
set @i += 1
end
return
end
go
select * from daysBetween('2021-01-01','2021-01-05')
출력