-- 사용자정의함수

 

Select dbo.Hap(3, 5) As

Go

 

-- Hap(3, 5) => 8을출력하는함수

Create Function dbo.Hap(@a Int, @b Int)

       Returns Int -- 반환값에대한테이터형식을지정

As

       Begin

             --[1] Intput

             Declare @result Int

             --[2] Process

             Set @result = @a + @b

             --[3] Output

             Return @result             -- 반환

       End

Go    

 

 

-- MyPower(2, 10) => 2 ^ 10 = 1024 출력

Select dbo.MyPower(2, 10) -- 1024

Go

 

-- MyPower 함수설계???

Create Function dbo.MyPower(@n Int, @c Int)

       Returns Int

As

       Begin        

             Declare @result Int                    

             Set @result = 1                               -- 곱하기위해서1로초기화

            

             Declare @i Int

             Set @i = 1

             While @i <= @c

             Begin

                    Set @result = @result * @n -- 카운트만큼곱하기

                    Set @i = @i + 1

             End

            

             Return @result                         

       End

Go

 

 

-- MyAbs() : 절대값

Select dbo.MyAbs(-10)      -- 10

Go

 

 

-- MyAbs 함수설계하기

Alter Function dbo.MyAbs(@n Int)

       Returns Int

As

       Begin

             --[1] Input

             Declare @result Int

             --[2] Process

             If @n < 0

                    Set @result = -@n

             Else

                    Set @result = @n

             --[3] Output

             Return @result     

       End

Go

 

 

-- dbo.Even(100) : 1~100까지짝수의합

-- dbo.Even(1000) : 1~1000까지짝수의합

Select dbo.Even(100)

Go

Select dbo.Even(1000)

Go

 

Create Function dbo.Even(@n Int)

       Returns Int 

As

       Begin 

             Declare @sum Int          

             Set @sum = 0

             Declare @i Int

            

             Set @i = 1

             While @i <= @n            

             Begin 

                    If @i % 2 = 0

                    Begin

                           Set @sum = @sum + @i

                    End

                    Set @i = @i + 1

             End

            

             Return @sum

       End

Go


Posted by holland14
: