User Defined Function
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