How to create scalar function?

762    Asked by JoshuaSmith in SQL Server , Asked on Jan 10, 2020
Answered by Rachit Gupta

Scalar functions are functions which return only a single value of any SQL type. Function can accept up to 1024 input parameters. Value can only be returned by the keyword return. Sample for the function:

Syntax:

Create function functionname( @input_paramters datatype)

Return data type

As

Begin

Return output_value

end

Sample for the function:

CREATE FUNCTION udfNet_value_test(

 @p_quantity INT,

 @p_list_price DEC(10,2),

 @p_discount DEC(4,2)

)

RETURNS DEC(10,2)

AS

BEGIN

 RETURN @p_quantity * @p_list_price * (1 - @p_discount);

END;

This will accept the quantity, list price and discount and give back the total bill price of the product

Sample data: quantity=10, cost of each product: 50, discount is 5%

select dbo.udfNet_value_test(10,50,0.05)

output is : 475.00



Your Answer

Interviews

Parent Categories