What is UDF in SQL SERVER PART 15 With Example Code

It looks like you've executed the provided code successfully. Here's a breakdown of what each part of the code does:

Drop Existing Scalar UDF: This part checks if the function CalculateCircleArea already exists as a scalar UDF('FN' stands for scalar function), and if it does, it drops it.

Create Scalar UDF: This section creates a scalar UDF named CalculateCircleArea, which calculates the area of a circle based on the provided radius.




Use Scalar UDF: Here, a variable @circleRadius is declared and assigned a value of 5.0.Then, the scalar UDF CalculateCircleArea is called with this radius value, and the result is displayed as CircleArea.

Drop Existing Scalar UDF(Again): Similar to the first step, this part checks if the function CalculateCircleArea exists as a scalar UDF and drops it if it does.

Create Table - Valued UDF: This section creates a table - valued UDF with the same name CalculateCircleArea.This UDF returns a table with columns Area and Circumference, calculated based on the provided radius.

Use Table - Valued UDF: Finally, a variable @circleRadius is declared and assigned a value of 5.0 again.The table - valued UDF CalculateCircleArea is then called with this radius value, and the result is displayed as CircleData.


-- Drop the existing scalar UDF if it exists

IF OBJECT_ID('dbo.CalculateCircleArea', 'FN') IS NOT NULL

    DROP FUNCTION dbo.CalculateCircleArea;

GO

 

-- Create Scalar UDF

CREATE FUNCTION CalculateCircleArea (@radius FLOAT)

RETURNS FLOAT

AS

BEGIN

    DECLARE @area FLOAT;

    SET @area = PI() * POWER(@radius, 2);

    RETURN @area;

END;

GO

 

-- Use Scalar UDF

DECLARE @circleRadius FLOAT = 5.0;

SELECT dbo.CalculateCircleArea(@circleRadius) AS CircleArea;

GO

 

-- Drop the existing scalar UDF if it exists

IF OBJECT_ID('dbo.CalculateCircleArea', 'FN') IS NOT NULL

    DROP FUNCTION dbo.CalculateCircleArea;

GO

 

-- Create Table-Valued UDF

CREATE FUNCTION CalculateCircleArea (@radius FLOAT)

RETURNS TABLE

AS

RETURN

(

    SELECT

        Area = PI() * POWER(@radius, 2),

        Circumference = 2 * PI() * @radius

);

GO

 

-- Use Table-Valued UDF

DECLARE @circleRadius FLOAT = 5.0;

SELECT * FROM dbo.CalculateCircleArea(@circleRadius) AS CircleData;

GO