본문 바로가기
백엔드/SQL

[SQL] User-defined Function(2)

by leejiwoo21 2021. 12. 3.

User-defined Function(2)

 

같은 이름의 함수를 여러번 생성할 때 추가하면 편한 코드

(1)

IF object_id('스키마이름.함수이름') is not null Drop function 스키마이름.함수이름
GO

(2)

if exists ( select * from sys.objects
			where object_id = object_id('함수이름'))
            drop function 함수이름
GO

> (1) 과 (2) 중에 골라서 쓰면 됩니다.

> 이 코드를 create function 전에 추가하면 이미 만들었던 함수를 삭제하고 다시 생성해서 오류가 나지 않습니다.

 

 

 

Scalar Function 

 

예제 (1)

IF object_id('dbo.CalculateArea') is not null Drop Function dbo.CalculateArea
go

create function dbo.CalculateArea( @radius as float )
returns float
as
begin
	return PI()*power(@radius,2)
end
go

select dbo.CalculateArea(2) as 'Area'

출력

 

 

 

예제 (2)

if object_id('dbo.getAge') is not null Drop Function dbo.getAge
go

create function dbo.getAge( @birthday as date )
returns int
as
begin
	return Datediff(year, @birthday, sysdatetime())
end
go

select dbo.getAge('1998-12-05') as 'Age'

 

출력

 

 

 

예제 (3)

if exists ( select * from sys.objects
			where object_id = object_id('dbo.rectangleArea'))
            drop function dbo.rectangleArea
GO

create function dbo.rectangleArea( @Width int, @Height int)
returns int
as
begin
	return ( @Width * @Height )
end
go

select dbo.rectangleArea(3,4) as 'Area'

출력

 

'백엔드 > SQL' 카테고리의 다른 글

[SQL] User-defined Function (4)  (0) 2021.12.04
[SQL] User-defined Function (3)  (0) 2021.12.04
[SQL] User-Defined Functions (1)  (0) 2021.12.03
[SQL] WHILE  (0) 2021.12.02
[SQL] IF...ELSE  (0) 2021.12.02

댓글