0% found this document useful (0 votes)
73 views

User Defined Function

This document describes a simple scalar user defined function (UDF) in TSQL that returns a delivery price based on a customer's location. The UDF takes country and city as parameters, sets a default price of 45 euros, and returns different prices for Iceland (8.15) and Poland depending on whether the city is Warsaw (7.85) or not (9.75). The UDF is called using an EXECUTE command to return a price for a specific country and city, or in a SELECT statement to return delivery prices for multiple customers.

Uploaded by

ddcv
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views

User Defined Function

This document describes a simple scalar user defined function (UDF) in TSQL that returns a delivery price based on a customer's location. The UDF takes country and city as parameters, sets a default price of 45 euros, and returns different prices for Iceland (8.15) and Poland depending on whether the city is Warsaw (7.85) or not (9.75). The UDF is called using an EXECUTE command to return a price for a specific country and city, or in a SELECT statement to return delivery prices for multiple customers.

Uploaded by

ddcv
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

11/5/2014

User Defined Function

TSQL>SimpleScalarUDF(UserDefinedFunction)inTSQL
ThisUDFfunctionreturnsdeliverypricedependingoncustomer'slocation:
IFEXISTS(SELECT*FROMsys.objects
WHEREobject_id=OBJECT_ID(N'[dbo].[fn_getdeliveryprice]')
ANDtypein(N'FN',N'IF',N'TF',N'FS',N'FT'))
DROPFUNCTION[dbo].[fn_getdeliveryprice]
GO
CREATEFUNCTIONdbo.fn_getdeliveryprice
(@countryVarchar(50),@cityVarchar(50))RETURNSFloat
AS
BEGIN
DECLARE@topayFloat
/*
fornotidentifiedcustomer'slocationdeliverypriceis45euro
*/
SET@topay=45
IF@country='iceland'
BEGIN
SET@topay=8.15
END
IF@country='poland'
BEGIN
IF@city='warsaw'
SET@topay=7.85
ELSE
SET@topay=9.75
END
/*...heremorepriceoptionscanbeplaced...*/
RETURN@topay
END
GRANTEXECUTEONOBJECT::[dbo].[fn_getdeliveryprice]TOgeorge
GO

ThenwecancallthisfunctionusingEXECUTEcommand:
DECLARE@myPriceFLOAT
EXEC@myPrice=dbo.fn_getdeliveryprice'poland','krakow'
PRINT@myPrice
Recivinginthemessagewindow:9.75
OrcallfunctionforeveryrowinSELECTstatement:
SELECTCustomerID,CustomerName,dbo.fn_getdeliveryprice(Country,
City)ASDelivPay
FROMCustomers
WHERECustomerID<3
Theresultswillcameasfollowing:
CustomerID

CustomerName

DelivPay

AngelinaAlba

28.5

JessicaSimpson

8.15

sqlexamples.info

http://www.sqlexamples.info/SQL/tsql_udf1.htm

1/1

You might also like