Cari Blog Ini

19 Juni 2012

Example of Create Function in SQL with Returns Value


1.A. Create Function with parameter
------------------------------------------------------------
-----code:start
------------------------------------------------------------
CREATE Function [Rate_Discount] (@Discount_1 as float,@Rate as float,@OGross as float)
RETURNS Float
AS
BEGIN
    Declare @Discount Float
     
    Select @Discount= (@Discount_1*@Rate)/(@OGross*@Rate+@Discount_1*@Rate)*100
   
    if @Discount is null
    Select @Discount=0
     
    return(@Discount)
End
------------------------------------------------------------
-----code:end
------------------------------------------------------------

Result Messages:
Command(s) completed successfully.


1.B.
How to use the function:
------------------------------------------------------------
-----code:start
------------------------------------------------------------
select dbo.[Rate_Discount] ('500000','1','100000000') as Rate_Discount_Value
------------------------------------------------------------
-----code:end
------------------------------------------------------------

Result Messages:
Rate_Discount_Value
----------------------
0.497512437810945

(1 row(s) affected)


1.C.
To remove the function:
------------------------------------------------------------
-----code:start
------------------------------------------------------------
DROP Function [Rate_Discount]
------------------------------------------------------------
-----code:end
------------------------------------------------------------



About :

01 - Create Function with Return Table in SQL Server
02 - Syntax : CREATE FUNCTION - Return Table - With Parameters
03 - Example of Create Function in SQL with Returns Value
04 - Example of Create Function (No Parameter) in SQL with Returns Value
05 - How to Use Function Intersect
06 - How to Use Function Except