User-defined function

A user-defined function (UDF) is a function provided by the user of a program or environment, in a context where the usual assumption is that functions are built into the program or environment. UDFs are usually written for the requirement of its creator.

BASIC language

In some old implementations of the BASIC programming language, user-defined functions are defined using the "DEF FN" syntax. More modern dialects of BASIC are influenced by the structured programming paradigm, where most or all of the code is written as user-defined functions or procedures, and the concept becomes practically redundant.

COBOL language

In the COBOL programming language, a user-defined function is an entity that is defined by the user by specifying a FUNCTION-ID paragraph. A user-defined function must return a value by specifying the RETURNING phrase of the procedure division header and they are invoked using the function-identifier syntax. See the ISO/IEC 1989:2014 Programming Language COBOL standard for details.

As of May 2022, the IBM Enterprise COBOL for z/OS 6.4 (IBM COBOL) compiler contains support for user-defined functions.

Databases

In relational database management systems, a user-defined function provides a mechanism for extending the functionality of the database server by adding a function, that can be evaluated in standard query language (usually SQL) statements. The SQL standard distinguishes between scalar and table functions. A scalar function returns only a single value (or NULL), whereas a table function returns a (relational) table comprising zero or more rows, each row with one or more columns.

User-defined functions in SQL are declared using the CREATE FUNCTION statement. For example, a user-defined function that converts Celsius to Fahrenheit (a temperature scale used in USA) might be declared like this:

CREATE FUNCTION dbo.CtoF(Celsius FLOAT)
  RETURNS FLOAT
  RETURN (Celsius * 1.8) + 32

Once created, a user-defined function may be used in expressions in SQL statements. For example, it can be invoked where most other intrinsic functions are allowed. This also includes SELECT statements, where the function can be used against data stored in tables in the database. Conceptually, the function is evaluated once per row in such usage. For example, assume a table named Elements, with a row for each known chemical element. The table has a column named BoilingPoint for the boiling point of that element, in Celsius. The query

SELECT Name, CtoF(BoilingPoint)
  FROM Elements

would retrieve the name and the boiling point from each row. It invokes the CtoF user-defined function as declared above in order to convert the value in the column to a value in Fahrenheit.

Each user-defined function carries certain properties or characteristics. The SQL standard defines the following properties:

  • Language - defines the programming language in which the user-defined function is implemented; examples include SQL, C, C# and Java.
  • Parameter style - defines the conventions that are used to pass the function parameters and results between the implementation of the function and the database system (only applicable if language is not SQL).
  • Specific name - a name for the function that is unique within the database. Note that the function name does not have to be unique, considering overloaded functions. Some SQL implementations require that function names are unique within a database, and overloaded functions are not allowed.
  • Determinism - specifies whether the function is deterministic or not. The determinism characteristic has an influence on the query optimizer when compiling a SQL statement.
  • SQL-data access - tells the database management system whether the function contains no SQL statements (NO SQL), contains SQL statements but does not access any tables or views (CONTAINS SQL), reads data from tables or views (READS SQL DATA), or actually modifies data in the database (MODIFIES SQL DATA).

User-defined functions should not be confused with stored procedures. Stored procedures allow the user to group a set of SQL commands. A procedure can accept parameters and execute its SQL statements depending on those parameters. A procedure is not an expression and, thus, cannot be used like user-defined functions.

Some database management systems allow the creation of user defined functions in languages other than SQL. Microsoft SQL Server, for example, allows the user to use .NET languages including C# for this purpose. DB2 and Oracle support user-defined functions written in C or Java programming languages.

SQL Server 2000

There are three types of UDF in Microsoft SQL Server 2000: scalar functions, inline table-valued functions, and multistatement table-valued functions.

Scalar functions return a single data value (not a table) with RETURNS clause. Scalar functions can use all scalar data types, with exception of timestamp and user-defined data types. Inline table-valued functions return the result set of a single SELECT statement. Multistatement table-valued functions return a table, which was built with many TRANSACT-SQL statements.

User-defined functions can be invoked from a query like built‑in functions such as OBJECT_ID, LEN, DATEDIFF, or can be executed through an EXECUTE statement like stored procedures.

Performance Notes: 1. On Microsoft SQL Server 2000 a table-valued function which "wraps" a View may be much faster than the View itself. The following MyFunction is an example of a "function-wrapper" which runs faster than the underlying view MyView:

CREATE FUNCTION MyFunction()
    RETURNS @Tbl TABLE 
    (
        StudentID              VARCHAR(255),
        SAS_StudentInstancesID INT,
        Label                  VARCHAR(255),
        Value                  MONEY,
        CMN_PersonsID          INT
    )
AS
BEGIN
    INSERT @Tbl
    (
        StudentID,
        SAS_StudentInstancesID,
        Label,
        Value,
        CMN_PersonsID
    )
    SELECT 
        StudentID,
        SAS_StudentInstancesID,
        Label,
        Value,
        CMN_PersonsID
    FROM MyView -- where MyView selects (with joins) the same columns from large table(s)

    RETURN
END

2. On Microsoft SQL Server 2005 the result of the same code execution is the opposite: view is executed faster than the "function-wrapper".

User-defined functions are subroutines made of one or more Transact-SQL statements that can be used to encapsulate code for reuse. It takes zero or more arguments and evaluates a return value. Has both control-flow and DML statements in its body similar to stored procedures. Does not allow changes to any Global Session State, like modifications to database or external resource, such as a file or network. Does not support output parameter. DEFAULT keyword must be specified to pass the default value of parameter. Errors in UDF cause UDF to abort which, in turn, aborts the statement that invoked the UDF.

CREATE FUNCTION CubicVolume
-- Input dimensions in centimeters
(
    @CubeLength decimal(4,1), 
    @CubeWidth  decimal(4,1),
    @CubeHeight decimal(4,1)
)
    RETURNS decimal(12,3)
AS
BEGIN
  RETURN(@CubeLength * @CubeWidth * @CubeHeight)
END

Data type supported in Microsoft SQL Server 2000 Like a temporary table used to store results Mostly used to define temporary variable of type (table) and the return value of a UDF The scope is limited to function, stored procedure, or batch in which it is defined Assignment operation is not allowed between (Table) variables May be used in SELECT, INSERT, UPDATE, and DELETE CREATE FUNCTION to create UDF ALTER FUNCTION to change the characteristics of UDF DROP FUNCTION to remove UDF

Apache Hive

Apache Hive defines, in addition to the regular user-defined functions (UDF), also user-defined aggregate functions (UDAF) and table-generating functions (UDTF).[1] Hive enables developers to create their own custom functions with Java.[2]

Apache Doris

Apache Doris, an open-source real-time analytical database, allows external users to contribute their own UDFs written in C++ to it.[3]

References

  1. ^ "LanguageManual UDF - Apache Hive - Apache Software Foundation". 26 June 2015.
  2. ^ "HivePlugins - Apache Hive - Apache Software Foundation". 26 June 2015.
  3. ^ "Apache Doris UDF". Retrieved 8 April 2023.

Read other articles:

Koordinat: 35°37′41″N 139°44′21″E / 35.628157°N 139.739099°E / 35.628157; 139.739099 Stasiun Shinagawa品川駅Tampak luar Stasiun ShinagawaLokasiPrefekturTokyo(Lihat stasiun lainnya di Tokyo)Distrik kotaMinatoAlamat3-chome, TakanawaKode pos108-0074Alamat dalam bahasa Jepang東京都港区高輪3丁目SejarahDibuka1872 (JR) • 1924 (Keikyū)Layanan kereta apiOperatorJR East, JR Central, KeikyūJalurJR EastJalur Tōkaidō • YokosukaKeihin-Tōhoku • Ya...

 

La Machine in the streets of Liverpool, September 2008 Paul St. George's Telectroscope installation at London City Hall (May 24, 2008), linking New York City and London, produced by Artichoke Light sculptures transform Leicester Square as part of Lumiere festival 2016 Artichoke, also known as the Artichoke Trust, is a London-based British company and registered charitable trust that stages arts spectacles and live events. It was founded in 2002 by Helen Marriage, former director of the Salisb...

 

National Civil Rights Museum Lorraine Motel Het National Civil Rights Museum is het Amerikaanse nationale burgerrechtenmuseum. Het museum is gevestigd in het voormalige Lorraine Motel in Memphis in de Verenigde Staten, waar in april 1968 de Amerikaanse burgerrechtenactivist Martin Luther King werd vermoord. Na de moord op King bleef het motel geopend tot in 1982. Een stichting die zich beijverde voor zijn nagedachtenis, de Martin Luther King Jr. Memorial Foundation kocht het gebouw in decembe...

Municipio de Mill Municipio Municipio de MillUbicación en el condado de Baxter en Arkansas Ubicación de Arkansas en EE. UU.Coordenadas 36°23′33″N 92°13′44″O / 36.3925, -92.2289Entidad Municipio • País  Estados Unidos • Estado  Arkansas • Condado BaxterSuperficie   • Total 132.5 km² • Tierra 109.1 km² • Agua (17.66%) 23.39 km²Altitud   • Media 189 m s. n. m.Población (2010)  ...

 

غمزة عين. غمزة العين هي أحد تعابير الوجه والذي يتم عن طريق إغلاق أحد العينين لوقت قصير.[1][2][3] تعتبر غمزة العين من أحد أشكال التواصل اللالفظي والتي عادة ما تتضمن معلومات أو نوايا مخفية، أو قد تكون مصحوبة أحيانا بانجذاب جنسي. معاني غمزة العين تبادل معلومات سرية تس...

 

Amphiglossus astrolabi Status konservasiRisiko rendahIUCN172920 TaksonomiKerajaanAnimaliaFilumChordataKelasReptiliaOrdoSquamataFamiliScincidaeGenusAmphiglossusSpesiesAmphiglossus astrolabi DistribusiEndemikMadagaskar lbs Diving skink (Amphiglossus astrolabi) adalah sebuah spesies skink. Spesies tersebut adalah endemik di Madagaskar. Spesies tersebut pertama kali dideskripsikan oleh André Marie Constant Duméril dan Gabriel Bibron pada tahun 1839.[2] Referensi ^ Vences, M. (2011). Amp...

Родовий АльянсКраїна  ТуреччинаГолова партії Сінан ОганДата заснування 11 березня 2023Дата розпуску 22 травня 2023Ідеологія КемалізмТурецький націоналізмНаціонал-консерватизманти-міграціяПарламентаризмПозиція УльтраправіМісць у  1 / 600 / <div error>Помилка вира...

 

This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Peggy album – news · newspapers · books · scholar · JSTOR (October 2021) (Learn how and when to remove this template message) 1977 studio album by Peggy LeePeggyStudio album by Peggy LeeReleased1977RecordedMarch 7–9, 1977StudioCBS Studios, London...

 

كريستوفر وود معلومات شخصية الميلاد 5 نوفمبر 1935[1][2]  لامبث  [لغات أخرى]‏  الوفاة 9 مايو 2015 (79 سنة) [3][1]  لندن  مواطنة المملكة المتحدة  الحياة العملية المدرسة الأم مدرسة الكلية الملكية  [لغات أخرى]‏جامعة كامبريدج  المهنة كاتب،  و...

Log HorizonSampul novel ringan volume pertama menampilkan karakter utama Akatsuki, Naotsugu dan Shiroeログ・ホライズン(Rogu Horaizun)GenrePetualangan, Fantasi, Fiksi ilmiah[1] Seri novelPengarangMamare TounoIlustratorKazuhiro HaraPenerbitEnterbrainPenerbit bahasa InggrisNA Yen PressTerbit31 Maret 2011 – sekarangVolume9 Manga Log Horizon Gaiden: Honey Moon Logs Log Horizon Log Horizon: The West Wind Brigade Log Horizon Gaiden: Nyanta-honcho Shiawase no Recipe Seri animeSutrad...

 

1899–1903 Korean Empire company Keijin Railway LPNative name京仁鐵道合資会社경인철도 합자회사Romanized nameHepburn: Keijin Tetsudō gōshi gaishaRR: Gyeongin Cheoldo HabjahoesaTypeGōshi gaisha (limited partnership)IndustryLand transportFounded15 May 1899Defunct1 November 1903FateAbsorbedSuccessorGyeongbu RailwayHeadquartersGyeongseong, Korean EmpireArea servedKorea (Seoul–Incheon)Key peoplePresident: Shibusawa EiichiServicesPassenger & freight railways Legend Gyeongin...

 

American philosopher FRSCThomas Lee PangleBorn1944 (age 78–79)Gouverneur, New York, U.S.NationalityAmericanEducationCornell University (PhD)University of Chicago (PhD)OccupationPolitical scientistSpouseLorraine Smith Pangle Thomas Lee Pangle, FRSC (born 1944) is an American political scientist. He holds the Joe R. Long Chair in Democratic Studies in the Department of Government and is Co-Director of the Thomas Jefferson Center for Core Texts and Ideas at the University of Texas at ...

Species of New World monkey Hairy saki Illustration by Gustav Mützel Conservation status Least Concern (IUCN 3.1)[1] Scientific classification Domain: Eukaryota Kingdom: Animalia Phylum: Chordata Class: Mammalia Order: Primates Suborder: Haplorhini Infraorder: Simiiformes Family: Pitheciidae Genus: Pithecia Species: P. hirsuta Binomial name Pithecia hirsutaSpix, 1823 The hairy saki (Pithecia hirsuta) is a species of saki monkey, a type of New World monkey. It is found in no...

 

Cemetery in Wandsworth, London St. Mary's Cemetery, Wandsworth St Mary's Cemetery is a cemetery opened in 1860 in Wandsworth, London. It was established by St Mary's Burial Board in part of Wandsworth Common. It has also been known as Battersea St Mary's Cemetery and Battersea Rise Cemetery. Its burial land was exhausted in the 1960s. There is a small chapel where services can be conducted. It is owned by the London Borough of Wandsworth. Notable burials include: John Burns, trade unionist an...

 

This biography of a living person needs additional citations for verification. Please help by adding reliable sources. Contentious material about living persons that is unsourced or poorly sourced must be removed immediately from the article and its talk page, especially if potentially libelous.Find sources: N. Leelakrishnan – news · newspapers · books · scholar · JSTOR (November 2021) (Learn how and when to remove this template message) Narayanaswamy ...

Destroyer of the French Navy A postcard of sister ship Sarbacane underway in 1905 History France NameSagaie NamesakeAssegai Ordered1900 BuilderForges et Chantiers de la Méditerranée, La Seyne-sur-Mer Laid down1901 Launched15 November 1902 Stricken1 October 1920 FateSold for scrap, 12 April 1921 General characteristics Class and typeArquebuse-class destroyer Displacement357 t (351 long tons) (deep load) Length56.58 m (185 ft 8 in) (o/a) Beam6.38 m (20 ft 11 ...

 

1839 novel by Frederick Marryat For other uses, see Phantom Ship (disambiguation). The Phantom Ship Frontispiece to the 1847 editionAuthorFrederick MarryatLanguageEnglishGenreGothic novelPublisherE.L. Carey & A. HartPublication dateMay 1839OCLC1711835TextThe Phantom Ship at Wikisource The Phantom Ship (1839) is a Gothic novel by Frederick Marryat which explores the legend of the Flying Dutchman. Plot introduction The plot concerns the quest of Philip Vanderdecken of Terneuzen in the Nethe...

 

Proverbs 5← chapter 4chapter 6 →The whole Book of Proverbs in the Leningrad Codex (1008 C.E.) from an old fascimile edition.BookBook of ProverbsCategoryKetuvimChristian Bible partOld TestamentOrder in the Christian part21 Proverbs 5 is the fifth chapter of the Book of Proverbs in the Hebrew Bible or the Old Testament of the Christian Bible.[1][2] The book is a compilation of several wisdom literature collections, with the heading in 1:1 may be intended to regard ...

2016 single by KehlaniGangstaSingle by Kehlanifrom the album Suicide Squad: The Album and SweetSexySavage (deluxe edition) ReleasedAugust 1, 2016Recorded2016StudioAtlantic Studios (Los Angeles, California)GenreAlternative R&BLength2:57LabelAtlanticSongwriter(s) Kehlani Parrish Skylar Grey[1] Andrew Swanson Jeremy Coleman Jason Evigan Jacob Luttrell Producer(s) JMIKE Djemba Djemba Kehlani singles chronology Distraction (2016) Gangsta (2016) Keep On (2017) Suicide Squad sing...

 

This article is about the Anglo-American poetry movement. For the contemporaneous Russian poetry movement, see Imaginism. 20th-century poetry movement The expatriate American poet Ezra Pound collected eleven poets in the first anthology of Imagist poetry, Des Imagistes (1914). (Pound photographed in 1913) Imagism was a movement in early-20th-century Anglo-American poetry that favored precision of imagery and clear, sharp language. It is considered to be the first organized modernist literary ...

 

Strategi Solo vs Squad di Free Fire: Cara Menang Mudah!