DataBase/MS SQL

22.MS_SQL 2008 - 사용자 정의 함수 [1]

Godffs 2009. 9. 14. 10:21
반응형

자신이 직접 없는 기능을 함수로 만들어보는 예제입니다.
tempdb에서 작업 합니다.
확인은 tempdb-프로그래밍기능-함수-스칼라 반환 함수-생성한 함수 확인


--사용자정의함수

Select dbo.Hap(3, 5) As

Go

 

--Hap(3, 5) => 8을출력하는함수_만들기~

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

       Returns Int --반환값에대한데이터형식

As

       Begin

             --[1] Input

             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(2, 10) 함수설계

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

 

Create 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



반응형