반환 값은 스칼라 (단일) 값이거나 테이블 또는 result set.
단일 데이터 값 반환
테이블 형식을 반환
CREATE [ OR ALTER ] FUNCTION [ schema_name. ] function_name
( [ { @parameter_name [ AS ][ type_schema_name. ] parameter_data_type
[ = default ] [ READONLY ] }
[ ,...n ] ]
)
RETURNS return_data_type
[ WITH <function_option> [ ,...n ] ]
[ AS ]
BEGIN
function_body
RETURN scalar_expression
END [ ; ]
create function getSum(@a int =20, @b int, @c int)
returns int
as
begin
declare @d as int
set @d = @a + @b + @c
return @d
end;
go
Incorrect syntax 'CREATE FUNCTION'must be the only statement in the batch.
이렇게 뜨면 위 아래에 go가 안들어갔는지 확인해서 넣어주면 된다. (batch 구역을 나누어주기 위해서)
이렇게 확인할 수 있다.
select dbo.getSum(3,5,7);
select dbo.getSum(default,5,7); --디폴트 쓸때
이렇게 실행시켜볼 수 있다.
ALTER function [dbo].[getSum](@a int=30, @b int=20, @c int =10)
returns int
as
begin
declare @d as int
set @d = @a + @b + @c
return @d
end;
drop function dbo.getSum
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(3.7);
IF OBJECT_ID('dbo.GetAge') IS NOT NULL DROP FUNCTION dbo.GetAge;
GO
CREATE FUNCTION dbo.GetAge(@birthdate AS DATE)
RETURNS INT
AS
BEGIN
RETURN DATEDIFF(year, @birthdate, sysdatetime());
END;
GO
select dbo.GetAge('1995-10-10')
GO
IF OBJECT_ID('dbo.rectangleArea') IS NOT NULL DROP FUNCTION dbo.rectangleArea;
GO
CREATE FUNCTION RectangleArea(@Width int, @Height int)
RETURNS int AS
BEGIN
RETURN ( @Width * @Height )
END
GO
select dbo.rectangleArea(4,8) as Area
IF OBJECT_ID('dbo.reverseCustName') IS NOT NULL DROP FUNCTION dbo.reverseCustName;
GO
CREATE FUNCTION dbo.reverseCustName(@str varchar(100))
RETURNS varchar(100)
AS
BEGIN
DECLARE @custName varchar(100)
set @custName = REVERSE(@str)
RETURN @custName
END
GO
select dbo.reverseCustName('hyunjune')
GO
USE AdventureWorks2019;
GO
IF OBJECT_ID (N'dbo.ufnGetInventoryStock', N'FN') IS NOT NULL
DROP FUNCTION ufnGetInventoryStock;
GO
CREATE FUNCTION dbo.ufnGetInventoryStock(@ProductID int)
RETURNS int
AS
-- Retunrs
BEGIN
DECLARE @ret int;
SELECT @ret = SUM(p.Quantity)
FROM Production.ProductInventory p
WHERE p.ProductID = @ProductID
AND p.LocationID = '6';
IF (@ret IS NULL)
SET @ret = 0;
RETURN @ret;
END;
GO
select dbo.ufnGetInventoryStock(4)