SlideShare ist ein Scribd-Unternehmen logo
1 von 5
Downloaden Sie, um offline zu lesen
Understand when to use user-defined functions in SQL Server | TechRepublic



   ZDNet Asia    SmartPlanet    TechRepublic                                                                                     Log In   Join TechRepublic   FAQ   Go Pro!




                                                    Blogs     Downloads       Newsletters       Galleries      Q&A     Discussions        News
                                               Research Library


     IT Management             Development         IT Support         Data Center        Networks         Security




     Home / Blogs / The Enterprise Cloud                                                   Follow this blog:

     The Enterprise Cloud


     Understand when to use user-
     defined functions in SQL
     Server
     By Tim Chapman
     September 3, 2007, 11:49 PM PDT

     In the simplest terms, a user-defined function (UDF) in SQL Server is a programming construct
     that accepts parameters, does work that typically makes use of the accepted parameters, and
     returns a type of result. This article will cover two types of UDFs: table-valued and scalar-valued.
     (I will not be covering aggregate functions.)




     Types of UDFs
     Table-valued functions
     A table-valued UDF is a function that accepts parameters and returns the results in the form of a
     table. This type of function is special because it returns a table that you can query the results of
     and join with other tables. In SQL Server 2005, field values from other tables may be passed into
     the function during a join operation to return a record based result. To accomplish this, you must
     use SQL Server 2005’s APPLY operator.

     It can be difficult to know when it is appropriate to use a VIEW vs. when it is appropriate to use a
     table-valued UDF. VIEWs are a great tool for data abstraction, combining data, and logically using
     subsets of data. I like to use table-valued UDFs when I need to use one or more values from
     different tables in a join operation where some type of calculation needs to be done and an
     aggregation returned.

     Scalar-valued functions
     A scalar-valued UDF accepts parameters and, ultimately, returns a single, atomic value. There are
     seven reasons why these types of functions are different than stored procedures in the database
     engine.

        You cannot modify data inside of a UDF.
        A scalar-valued UDF returns only one value, where a stored procedure can have numerous
        OUTPUT parameters.
        You can use scalar-valued UDFs as the default value for a column in a table.
        Scalar-valued UDFs are an easy way to define constant values to use in your database
        environment.
        You can pass field values as parameters into UDFs.



http://www.techrepublic.com/blog/datacenter/understand-when-to-use-user-defined-functions-in-sql-server/171[08/29/2012 3:08:18 PM]
Understand when to use user-defined functions in SQL Server | TechRepublic

           You can nest scalar function calls. This means that you can pass a call to a scalar-valued
           function to another function or stored procedure.
           You can use the results from scalar-valued UDFs as criteria in a WHERE statement. Although
           you can do it, this is typically not a good idea. (Later in the article, I’ll explain why I try to avoid
           this common practice.)

     There are two types of scalar-valued UDFs: deterministic and non-deterministic. Recognizing the
     determinism of the functions that are created is important. An example of the importance is the
     creation of indexed views. One of the many restrictions of creating an index on a view is that the
     view definition cannot use a non-deterministic function.

     Deterministic
     A deterministic UDF always returns the same result with the same set of input parameters. Some
     examples of deterministic functions are the system functions MONTH(), YEAR(), and ISNULL().

     Non-deterministic
     A non-deterministic UDF is can potentially return a different value each time it is called with the
     same set of input parameters. Some examples of non-deterministic functions are the system
     functions GETDATE(), NEWID(), and @@CONNECTIONS.

     Two examples of UDFs
     Before presenting the examples, I will set up my SalesHistory table and load data into it:

     IF OBJECT_ID('SalesHistory')>0
            DROP TABLE SalesHistory;

      CREATE TABLE [dbo].[SalesHistory]
      (
            [SaleID] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
            [Product] [varchar](10) NULL,
            [SaleDate] [datetime] NULL,
            [SalePrice] [money] NULL
      )

      DECLARE @i SMALLINT
      SET @i = 1

      WHILE (@i <=1000)
      BEGIN

              INSERT INTO SalesHistory(Product, SaleDate, SalePrice)
              VALUES ('Computer', DATEADD(mm, @i, '3/11/1919'), DATEPART(ms, GETDATE()) + (@i +
     57))

              INSERT INTO SalesHistory(Product, SaleDate, SalePrice)
              VALUES('BigScreen', DATEADD(mm, @i, '3/11/1927'), DATEPART(ms, GETDATE()) + (@i +
     13))

              INSERT INTO SalesHistory(Product, SaleDate, SalePrice)
              VALUES('PoolTable', DATEADD(mm, @i, '3/11/1908'), DATEPART(ms, GETDATE()) + (@i +
     29))

              SET @i = @i + 1
      END

      GO

     The first UDF I will look at is the scalar-valued UDF. The script below defines a function named
     dbo.udf_GetProductSales that accepts three parameters and returns a MONEY value. The
     function uses the three input parameters as criteria in calculating the total sales from the
     SalesHistory table.

     CREATE FUNCTION dbo.udf_GetProductSales
      (
            @Product VARCHAR(10),
            @BeginDate DATETIME,
            @EndDate DATETIME
      )
      RETURNS MONEY
      AS
      BEGIN
            DECLARE @Sales MONEY




http://www.techrepublic.com/blog/datacenter/understand-when-to-use-user-defined-functions-in-sql-server/171[08/29/2012 3:08:18 PM]
Understand when to use user-defined functions in SQL Server | TechRepublic

            SELECT @Sales = SUM(SalePrice)
            FROM SalesHistory
            WHERE
                  Product = @Product AND
      SaleDate BETWEEN @BeginDate AND @EndDate

              RETURN(@Sales)
      END

     The script below calls the UDF created in the above script. Note: The schema the function
     belongs to must be used in the call. In this case, the function belongs to the dbo schema.

     SELECT dbo.udf_GetProductSales('PoolTable', '1/1/1990', '1/1/2000')

     I usually discourage using scalar-valued UDFs in a WHERE criteria statement because, for every
     record considered in the query, the scalar-valued function will be called. This means that a
     function used in the WHERE criteria will cause a scan of the values being searched, which is
     going to be slower than if an index is able to be used. (I will provide more details on this concept
     in a future article.)

     Although the use of a correlated sub-query is sometimes confusing and complicated, the use of
     them can help solve some of the more challenging query problems. While using these special
     queries is useful, they only return one column of data. You can use the upgraded table-valued
     UDFs in SQL Server 2005 to overcome this shortcoming. I’ll show you how to use the APPLY
     operator to accept column values from a table and return a table-result of correlated values.

     CREATE FUNCTION dbo.udf_GetProductSalesTable
      (
            @Product VARCHAR(10),
            @SaleID INT
      )
      RETURNS @SalesTable TABLE
      (
            SalesTotal MONEY,
            SalesCount INT
      )

      BEGIN

              INSERT INTO @SalesTable(SalesTotal, SalesCount)
              SELECT
                    SUM(SalePrice), COUNT(SaleID)
              FROM
                    SalesHistory
              WHERE
                    Product = @Product AND
                    SaleID <= @SaleID

              RETURN
      END
      GO

     The above function accepts the particular product for which we were searching, along with the
     SaleID from the SalesHistory table. From the function definition, you can see that the function
     returns a table named @SalesTable that contains two columns: SalesTotal and SalesCount. The
     body of the function inserts aggregate values into the @SalesTable table variable based upon the
     input parameters.

     The following code uses the APPLY operator to invoke the table-valued function with the values
     from the SalesHistory table. (Note: Logically, you may want to use a JOIN operator here, but it is
     not necessary. The APPLY operator essentially does the “JOIN” for us by applying the values from
     the SalesHistory table to the table-valued function. In a sense, this code works the same way a
     correlated sub-query does, except that it can return multiple correlated values.)

     SELECT * FROM SalesHistory sh
      CROSS APPLY dbo.udf_GetProductSalesTable(sh.Product, sh.SaleID)
      ORDER BY sh.SaleID ASC

     Additional TechRepublic resources on UDFs
        SQL Server 2000’s user-defined functions add flexibility, cut coding time
        Building and using table UDFs in SQL Server
        Incorporate SQL Server UDFs in your .NET applications




http://www.techrepublic.com/blog/datacenter/understand-when-to-use-user-defined-functions-in-sql-server/171[08/29/2012 3:08:18 PM]
Understand when to use user-defined functions in SQL Server | TechRepublic

     Tim Chapman is a SQL Server database administrator who works for a bank in Louisville, KY, and
     has more than 7 years of IT experience. He is also Microsoft certified in SQL Server 2000 and
     SQL Server 2005. If you would like to contact Tim, please e-mail him at chapman.tim@gmail.com.
     —————————————————————————————–

     Get SQL tips in your inbox
     TechRepublic’s free SQL Server newsletter, delivered each Tuesday, contains hands-on tips that
     will help you become more adept with this powerful relational database management system.
     Automatically subscribe today!


     Get IT Tips, news, and reviews delivered directly to your inbox by subscribing to TechRepublic’s free
     newsletters.




                    About Tim Chapman
                        Full Bio     Contact




                   Talking intelligently about                    Defragment your Windows
                   virtualization                                 Server 2003 hard drive on a
                                                                  set schedule




         7            Join the conversation!                                              Add Your Opinion
      Comments        Follow via:



      Staff Picks      Top Rated       Most Recent      My Contacts                              See All Comments




                       UDF or View                                                                     0
                       pixelwiz 15th Jul 2011                                                        Votes


             Can you please give some more details on when it is more appropriate to use a View
             vs a table-valued UDF? I have a few table-valued UDFs created that now I feel
             maybe should have been views, but I... Read Whole Comment +


                 View in thread




                       Scalar UDF in Where Clause                                                      0
                       unclebiguns@... 13th Sep 2007                                                 Votes



             So you are saying that if I use the a Scalar UDF ona variable or parameter in a where
             clause, it will not use an index? For example: Select product_id, product_name from
             products where... Read Whole Comment +


                 View in thread




                       RE: Understand when to use user-defined functions in                            0
                       SQL Server                                                                    Votes

                       alaniane@... 7th Sep 2007

             Thanks for the article on UDFs. I also like to use UDFs when designing queries. It




http://www.techrepublic.com/blog/datacenter/understand-when-to-use-user-defined-functions-in-sql-server/171[08/29/2012 3:08:18 PM]
Understand when to use user-defined functions in SQL Server | TechRepublic

            makes it easier to break complex queries into smaller chunks for debugging
            purposes. Later on, I will replace the... Read Whole Comment +


               View in thread




                                                 See all comments



     Join the TechRepublic Community and join the conversation! Signing-up is
     free and quick, Do it now, we want to hear your opinion.

       Join       Login




http://www.techrepublic.com/blog/datacenter/understand-when-to-use-user-defined-functions-in-sql-server/171[08/29/2012 3:08:18 PM]

Weitere ähnliche Inhalte

Was ist angesagt?

Subqueries -Oracle DataBase
Subqueries -Oracle DataBaseSubqueries -Oracle DataBase
Subqueries -Oracle DataBaseSalman Memon
 
Aggregating Data Using Group Functions
Aggregating Data Using Group FunctionsAggregating Data Using Group Functions
Aggregating Data Using Group FunctionsSalman Memon
 
Manipulating Data Oracle Data base
Manipulating Data Oracle Data baseManipulating Data Oracle Data base
Manipulating Data Oracle Data baseSalman Memon
 
Les08 (manipulating data)
Les08 (manipulating data)Les08 (manipulating data)
Les08 (manipulating data)Achmad Solichin
 
mysql 1st. act.
mysql 1st. act.mysql 1st. act.
mysql 1st. act.von lozano
 
Writing Basic SQL SELECT Statements
Writing Basic SQL SELECT StatementsWriting Basic SQL SELECT Statements
Writing Basic SQL SELECT StatementsSalman Memon
 
Restricting and Sorting Data - Oracle Data Base
Restricting and Sorting Data - Oracle Data BaseRestricting and Sorting Data - Oracle Data Base
Restricting and Sorting Data - Oracle Data BaseSalman Memon
 

Was ist angesagt? (20)

Subqueries -Oracle DataBase
Subqueries -Oracle DataBaseSubqueries -Oracle DataBase
Subqueries -Oracle DataBase
 
plsql Les08
plsql Les08 plsql Les08
plsql Les08
 
Aggregating Data Using Group Functions
Aggregating Data Using Group FunctionsAggregating Data Using Group Functions
Aggregating Data Using Group Functions
 
SQL Tunning
SQL TunningSQL Tunning
SQL Tunning
 
Manipulating Data Oracle Data base
Manipulating Data Oracle Data baseManipulating Data Oracle Data base
Manipulating Data Oracle Data base
 
Oracle SQL Advanced
Oracle SQL AdvancedOracle SQL Advanced
Oracle SQL Advanced
 
Les08 (manipulating data)
Les08 (manipulating data)Les08 (manipulating data)
Les08 (manipulating data)
 
mysql 1st. act.
mysql 1st. act.mysql 1st. act.
mysql 1st. act.
 
plsql Les09
 plsql Les09 plsql Les09
plsql Les09
 
plsql Les07
plsql Les07 plsql Les07
plsql Les07
 
Database Objects
Database ObjectsDatabase Objects
Database Objects
 
plsql Lec11
plsql Lec11 plsql Lec11
plsql Lec11
 
Oracle Database View
Oracle Database ViewOracle Database View
Oracle Database View
 
Writing Basic SQL SELECT Statements
Writing Basic SQL SELECT StatementsWriting Basic SQL SELECT Statements
Writing Basic SQL SELECT Statements
 
Ch05
Ch05Ch05
Ch05
 
Ch04
Ch04Ch04
Ch04
 
Module 3
Module 3Module 3
Module 3
 
Restricting and Sorting Data - Oracle Data Base
Restricting and Sorting Data - Oracle Data BaseRestricting and Sorting Data - Oracle Data Base
Restricting and Sorting Data - Oracle Data Base
 
Lab1 select statement
Lab1 select statementLab1 select statement
Lab1 select statement
 
Oraclesql
OraclesqlOraclesql
Oraclesql
 

Ähnlich wie Understand when to use user defined functions in sql server tech-republic

05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptx05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptxKareemBullard1
 
Subqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactionsSubqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactionsmaxpane
 
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1Die Neuheiten in MariaDB 10.2 und MaxScale 2.1
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1MariaDB plc
 
Fix My Functions: TSQL User Defined Functions in SQL Server
Fix My Functions: TSQL User Defined Functions in SQL ServerFix My Functions: TSQL User Defined Functions in SQL Server
Fix My Functions: TSQL User Defined Functions in SQL ServerKendra Little
 
Avoiding cursors with sql server 2005 tech republic
Avoiding cursors with sql server 2005   tech republicAvoiding cursors with sql server 2005   tech republic
Avoiding cursors with sql server 2005 tech republicKaing Menglieng
 
08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadatarehaniltifat
 
Advanced plsql mock_assessment
Advanced plsql mock_assessmentAdvanced plsql mock_assessment
Advanced plsql mock_assessmentSaurabh K. Gupta
 
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...Jürgen Ambrosi
 
Oracle data integrator project
Oracle data integrator projectOracle data integrator project
Oracle data integrator projectAmit Sharma
 
Web Cloud Computing SQL Server - Ferrara University
Web Cloud Computing SQL Server  -  Ferrara UniversityWeb Cloud Computing SQL Server  -  Ferrara University
Web Cloud Computing SQL Server - Ferrara Universityantimo musone
 
Procedures/functions of rdbms
Procedures/functions of rdbmsProcedures/functions of rdbms
Procedures/functions of rdbmsjain.pralabh
 
AAO BI Portfolio
AAO BI PortfolioAAO BI Portfolio
AAO BI PortfolioAl Ottley
 
See sql server graphical execution plans in action tech republic
See sql server graphical execution plans in action   tech republicSee sql server graphical execution plans in action   tech republic
See sql server graphical execution plans in action tech republicKaing Menglieng
 
New features of sql server 2005
New features of sql server 2005New features of sql server 2005
New features of sql server 2005Govind Raj
 
Create column store index on all supported tables in sql server 2014 copy
Create column store index on all supported tables in sql server 2014    copyCreate column store index on all supported tables in sql server 2014    copy
Create column store index on all supported tables in sql server 2014 copyMustafa EL-Masry
 
Cursors, triggers, procedures
Cursors, triggers, proceduresCursors, triggers, procedures
Cursors, triggers, proceduresVaibhav Kathuria
 
Udf&views in sql...by thanveer melayi
Udf&views in sql...by thanveer melayiUdf&views in sql...by thanveer melayi
Udf&views in sql...by thanveer melayiMuhammed Thanveer M
 

Ähnlich wie Understand when to use user defined functions in sql server tech-republic (20)

05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptx05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptx
 
Subqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactionsSubqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactions
 
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1Die Neuheiten in MariaDB 10.2 und MaxScale 2.1
Die Neuheiten in MariaDB 10.2 und MaxScale 2.1
 
Fix My Functions: TSQL User Defined Functions in SQL Server
Fix My Functions: TSQL User Defined Functions in SQL ServerFix My Functions: TSQL User Defined Functions in SQL Server
Fix My Functions: TSQL User Defined Functions in SQL Server
 
Avoiding cursors with sql server 2005 tech republic
Avoiding cursors with sql server 2005   tech republicAvoiding cursors with sql server 2005   tech republic
Avoiding cursors with sql server 2005 tech republic
 
SQL Commands
SQL Commands SQL Commands
SQL Commands
 
08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata08 Dynamic SQL and Metadata
08 Dynamic SQL and Metadata
 
Advanced plsql mock_assessment
Advanced plsql mock_assessmentAdvanced plsql mock_assessment
Advanced plsql mock_assessment
 
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
2° Ciclo Microsoft CRUI 3° Sessione: l'evoluzione delle piattaforme tecnologi...
 
Oracle data integrator project
Oracle data integrator projectOracle data integrator project
Oracle data integrator project
 
Web Cloud Computing SQL Server - Ferrara University
Web Cloud Computing SQL Server  -  Ferrara UniversityWeb Cloud Computing SQL Server  -  Ferrara University
Web Cloud Computing SQL Server - Ferrara University
 
Procedures/functions of rdbms
Procedures/functions of rdbmsProcedures/functions of rdbms
Procedures/functions of rdbms
 
AAO BI Portfolio
AAO BI PortfolioAAO BI Portfolio
AAO BI Portfolio
 
See sql server graphical execution plans in action tech republic
See sql server graphical execution plans in action   tech republicSee sql server graphical execution plans in action   tech republic
See sql server graphical execution plans in action tech republic
 
New features of sql server 2005
New features of sql server 2005New features of sql server 2005
New features of sql server 2005
 
Create column store index on all supported tables in sql server 2014 copy
Create column store index on all supported tables in sql server 2014    copyCreate column store index on all supported tables in sql server 2014    copy
Create column store index on all supported tables in sql server 2014 copy
 
Oracle: Functions
Oracle: FunctionsOracle: Functions
Oracle: Functions
 
Oracle: Functions
Oracle: FunctionsOracle: Functions
Oracle: Functions
 
Cursors, triggers, procedures
Cursors, triggers, proceduresCursors, triggers, procedures
Cursors, triggers, procedures
 
Udf&views in sql...by thanveer melayi
Udf&views in sql...by thanveer melayiUdf&views in sql...by thanveer melayi
Udf&views in sql...by thanveer melayi
 

Mehr von Kaing Menglieng

What is your sql server backup strategy tech_republic
What is your sql server backup strategy    tech_republicWhat is your sql server backup strategy    tech_republic
What is your sql server backup strategy tech_republicKaing Menglieng
 
Using sql server 2008's merge statement tech republic
Using sql server 2008's merge statement   tech republicUsing sql server 2008's merge statement   tech republic
Using sql server 2008's merge statement tech republicKaing Menglieng
 
Using grouping sets in sql server 2008 tech republic
Using grouping sets in sql server 2008   tech republicUsing grouping sets in sql server 2008   tech republic
Using grouping sets in sql server 2008 tech republicKaing Menglieng
 
Sql server indexed views speed up your select queries part 1 - code-projec
Sql server indexed views   speed up your select queries  part 1 - code-projecSql server indexed views   speed up your select queries  part 1 - code-projec
Sql server indexed views speed up your select queries part 1 - code-projecKaing Menglieng
 
Sql server – query optimization – remove bookmark lookup – remove rid lookup
Sql server – query optimization – remove bookmark lookup – remove rid lookupSql server – query optimization – remove bookmark lookup – remove rid lookup
Sql server – query optimization – remove bookmark lookup – remove rid lookupKaing Menglieng
 
Sql server common interview questions and answers
Sql server   common interview questions and answersSql server   common interview questions and answers
Sql server common interview questions and answersKaing Menglieng
 
Sql server common interview questions and answers page 6
Sql server   common interview questions and answers page 6Sql server   common interview questions and answers page 6
Sql server common interview questions and answers page 6Kaing Menglieng
 
Sql server common interview questions and answers page 5
Sql server   common interview questions and answers page 5Sql server   common interview questions and answers page 5
Sql server common interview questions and answers page 5Kaing Menglieng
 
Sql server common interview questions and answers page 4
Sql server   common interview questions and answers page 4Sql server   common interview questions and answers page 4
Sql server common interview questions and answers page 4Kaing Menglieng
 
Sql server common interview questions and answers page 2
Sql server   common interview questions and answers page 2Sql server   common interview questions and answers page 2
Sql server common interview questions and answers page 2Kaing Menglieng
 
Sql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql seSql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql seKaing Menglieng
 
Speeding up queries with semi joins and anti-joins
Speeding up queries with semi joins and anti-joinsSpeeding up queries with semi joins and anti-joins
Speeding up queries with semi joins and anti-joinsKaing Menglieng
 
Speed up sql server apps - visual studio magazine
Speed up sql server apps  - visual studio magazineSpeed up sql server apps  - visual studio magazine
Speed up sql server apps - visual studio magazineKaing Menglieng
 
Reviewing sql server permissions tech republic
Reviewing sql server permissions   tech republicReviewing sql server permissions   tech republic
Reviewing sql server permissions tech republicKaing Menglieng
 
Query optimization how to search millions of record in sql table faster -
Query optimization   how to search millions of record in sql table faster  -Query optimization   how to search millions of record in sql table faster  -
Query optimization how to search millions of record in sql table faster -Kaing Menglieng
 
Optimize sql server queries with these advanced tuning techniques tech repu
Optimize sql server queries with these advanced tuning techniques   tech repuOptimize sql server queries with these advanced tuning techniques   tech repu
Optimize sql server queries with these advanced tuning techniques tech repuKaing Menglieng
 
New date datatypes in sql server 2008 tech republic
New date datatypes in sql server 2008   tech republicNew date datatypes in sql server 2008   tech republic
New date datatypes in sql server 2008 tech republicKaing Menglieng
 
Introduction to policy based management in sql server 2008 tech-republic
Introduction to policy based management in sql server 2008   tech-republicIntroduction to policy based management in sql server 2008   tech-republic
Introduction to policy based management in sql server 2008 tech-republicKaing Menglieng
 
Introduction to change data capture in sql server 2008 tech republic
Introduction to change data capture in sql server 2008   tech republicIntroduction to change data capture in sql server 2008   tech republic
Introduction to change data capture in sql server 2008 tech republicKaing Menglieng
 

Mehr von Kaing Menglieng (20)

What is your sql server backup strategy tech_republic
What is your sql server backup strategy    tech_republicWhat is your sql server backup strategy    tech_republic
What is your sql server backup strategy tech_republic
 
Using sql server 2008's merge statement tech republic
Using sql server 2008's merge statement   tech republicUsing sql server 2008's merge statement   tech republic
Using sql server 2008's merge statement tech republic
 
Using grouping sets in sql server 2008 tech republic
Using grouping sets in sql server 2008   tech republicUsing grouping sets in sql server 2008   tech republic
Using grouping sets in sql server 2008 tech republic
 
Sql server indexed views speed up your select queries part 1 - code-projec
Sql server indexed views   speed up your select queries  part 1 - code-projecSql server indexed views   speed up your select queries  part 1 - code-projec
Sql server indexed views speed up your select queries part 1 - code-projec
 
Sql server – query optimization – remove bookmark lookup – remove rid lookup
Sql server – query optimization – remove bookmark lookup – remove rid lookupSql server – query optimization – remove bookmark lookup – remove rid lookup
Sql server – query optimization – remove bookmark lookup – remove rid lookup
 
Sql server common interview questions and answers
Sql server   common interview questions and answersSql server   common interview questions and answers
Sql server common interview questions and answers
 
Sql server common interview questions and answers page 6
Sql server   common interview questions and answers page 6Sql server   common interview questions and answers page 6
Sql server common interview questions and answers page 6
 
Sql server common interview questions and answers page 5
Sql server   common interview questions and answers page 5Sql server   common interview questions and answers page 5
Sql server common interview questions and answers page 5
 
Sql server common interview questions and answers page 4
Sql server   common interview questions and answers page 4Sql server   common interview questions and answers page 4
Sql server common interview questions and answers page 4
 
Sql server common interview questions and answers page 2
Sql server   common interview questions and answers page 2Sql server   common interview questions and answers page 2
Sql server common interview questions and answers page 2
 
Sql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql seSql server – 2008 – hardware and software requirements for installing sql se
Sql server – 2008 – hardware and software requirements for installing sql se
 
Speeding up queries with semi joins and anti-joins
Speeding up queries with semi joins and anti-joinsSpeeding up queries with semi joins and anti-joins
Speeding up queries with semi joins and anti-joins
 
Speed up sql
Speed up sqlSpeed up sql
Speed up sql
 
Speed up sql server apps - visual studio magazine
Speed up sql server apps  - visual studio magazineSpeed up sql server apps  - visual studio magazine
Speed up sql server apps - visual studio magazine
 
Reviewing sql server permissions tech republic
Reviewing sql server permissions   tech republicReviewing sql server permissions   tech republic
Reviewing sql server permissions tech republic
 
Query optimization how to search millions of record in sql table faster -
Query optimization   how to search millions of record in sql table faster  -Query optimization   how to search millions of record in sql table faster  -
Query optimization how to search millions of record in sql table faster -
 
Optimize sql server queries with these advanced tuning techniques tech repu
Optimize sql server queries with these advanced tuning techniques   tech repuOptimize sql server queries with these advanced tuning techniques   tech repu
Optimize sql server queries with these advanced tuning techniques tech repu
 
New date datatypes in sql server 2008 tech republic
New date datatypes in sql server 2008   tech republicNew date datatypes in sql server 2008   tech republic
New date datatypes in sql server 2008 tech republic
 
Introduction to policy based management in sql server 2008 tech-republic
Introduction to policy based management in sql server 2008   tech-republicIntroduction to policy based management in sql server 2008   tech-republic
Introduction to policy based management in sql server 2008 tech-republic
 
Introduction to change data capture in sql server 2008 tech republic
Introduction to change data capture in sql server 2008   tech republicIntroduction to change data capture in sql server 2008   tech republic
Introduction to change data capture in sql server 2008 tech republic
 

Understand when to use user defined functions in sql server tech-republic

  • 1. Understand when to use user-defined functions in SQL Server | TechRepublic ZDNet Asia SmartPlanet TechRepublic Log In Join TechRepublic FAQ Go Pro! Blogs Downloads Newsletters Galleries Q&A Discussions News Research Library IT Management Development IT Support Data Center Networks Security Home / Blogs / The Enterprise Cloud Follow this blog: The Enterprise Cloud Understand when to use user- defined functions in SQL Server By Tim Chapman September 3, 2007, 11:49 PM PDT In the simplest terms, a user-defined function (UDF) in SQL Server is a programming construct that accepts parameters, does work that typically makes use of the accepted parameters, and returns a type of result. This article will cover two types of UDFs: table-valued and scalar-valued. (I will not be covering aggregate functions.) Types of UDFs Table-valued functions A table-valued UDF is a function that accepts parameters and returns the results in the form of a table. This type of function is special because it returns a table that you can query the results of and join with other tables. In SQL Server 2005, field values from other tables may be passed into the function during a join operation to return a record based result. To accomplish this, you must use SQL Server 2005’s APPLY operator. It can be difficult to know when it is appropriate to use a VIEW vs. when it is appropriate to use a table-valued UDF. VIEWs are a great tool for data abstraction, combining data, and logically using subsets of data. I like to use table-valued UDFs when I need to use one or more values from different tables in a join operation where some type of calculation needs to be done and an aggregation returned. Scalar-valued functions A scalar-valued UDF accepts parameters and, ultimately, returns a single, atomic value. There are seven reasons why these types of functions are different than stored procedures in the database engine. You cannot modify data inside of a UDF. A scalar-valued UDF returns only one value, where a stored procedure can have numerous OUTPUT parameters. You can use scalar-valued UDFs as the default value for a column in a table. Scalar-valued UDFs are an easy way to define constant values to use in your database environment. You can pass field values as parameters into UDFs. http://www.techrepublic.com/blog/datacenter/understand-when-to-use-user-defined-functions-in-sql-server/171[08/29/2012 3:08:18 PM]
  • 2. Understand when to use user-defined functions in SQL Server | TechRepublic You can nest scalar function calls. This means that you can pass a call to a scalar-valued function to another function or stored procedure. You can use the results from scalar-valued UDFs as criteria in a WHERE statement. Although you can do it, this is typically not a good idea. (Later in the article, I’ll explain why I try to avoid this common practice.) There are two types of scalar-valued UDFs: deterministic and non-deterministic. Recognizing the determinism of the functions that are created is important. An example of the importance is the creation of indexed views. One of the many restrictions of creating an index on a view is that the view definition cannot use a non-deterministic function. Deterministic A deterministic UDF always returns the same result with the same set of input parameters. Some examples of deterministic functions are the system functions MONTH(), YEAR(), and ISNULL(). Non-deterministic A non-deterministic UDF is can potentially return a different value each time it is called with the same set of input parameters. Some examples of non-deterministic functions are the system functions GETDATE(), NEWID(), and @@CONNECTIONS. Two examples of UDFs Before presenting the examples, I will set up my SalesHistory table and load data into it: IF OBJECT_ID('SalesHistory')>0 DROP TABLE SalesHistory; CREATE TABLE [dbo].[SalesHistory] ( [SaleID] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY, [Product] [varchar](10) NULL, [SaleDate] [datetime] NULL, [SalePrice] [money] NULL ) DECLARE @i SMALLINT SET @i = 1 WHILE (@i <=1000) BEGIN INSERT INTO SalesHistory(Product, SaleDate, SalePrice) VALUES ('Computer', DATEADD(mm, @i, '3/11/1919'), DATEPART(ms, GETDATE()) + (@i + 57)) INSERT INTO SalesHistory(Product, SaleDate, SalePrice) VALUES('BigScreen', DATEADD(mm, @i, '3/11/1927'), DATEPART(ms, GETDATE()) + (@i + 13)) INSERT INTO SalesHistory(Product, SaleDate, SalePrice) VALUES('PoolTable', DATEADD(mm, @i, '3/11/1908'), DATEPART(ms, GETDATE()) + (@i + 29)) SET @i = @i + 1 END GO The first UDF I will look at is the scalar-valued UDF. The script below defines a function named dbo.udf_GetProductSales that accepts three parameters and returns a MONEY value. The function uses the three input parameters as criteria in calculating the total sales from the SalesHistory table. CREATE FUNCTION dbo.udf_GetProductSales ( @Product VARCHAR(10), @BeginDate DATETIME, @EndDate DATETIME ) RETURNS MONEY AS BEGIN DECLARE @Sales MONEY http://www.techrepublic.com/blog/datacenter/understand-when-to-use-user-defined-functions-in-sql-server/171[08/29/2012 3:08:18 PM]
  • 3. Understand when to use user-defined functions in SQL Server | TechRepublic SELECT @Sales = SUM(SalePrice) FROM SalesHistory WHERE Product = @Product AND SaleDate BETWEEN @BeginDate AND @EndDate RETURN(@Sales) END The script below calls the UDF created in the above script. Note: The schema the function belongs to must be used in the call. In this case, the function belongs to the dbo schema. SELECT dbo.udf_GetProductSales('PoolTable', '1/1/1990', '1/1/2000') I usually discourage using scalar-valued UDFs in a WHERE criteria statement because, for every record considered in the query, the scalar-valued function will be called. This means that a function used in the WHERE criteria will cause a scan of the values being searched, which is going to be slower than if an index is able to be used. (I will provide more details on this concept in a future article.) Although the use of a correlated sub-query is sometimes confusing and complicated, the use of them can help solve some of the more challenging query problems. While using these special queries is useful, they only return one column of data. You can use the upgraded table-valued UDFs in SQL Server 2005 to overcome this shortcoming. I’ll show you how to use the APPLY operator to accept column values from a table and return a table-result of correlated values. CREATE FUNCTION dbo.udf_GetProductSalesTable ( @Product VARCHAR(10), @SaleID INT ) RETURNS @SalesTable TABLE ( SalesTotal MONEY, SalesCount INT ) BEGIN INSERT INTO @SalesTable(SalesTotal, SalesCount) SELECT SUM(SalePrice), COUNT(SaleID) FROM SalesHistory WHERE Product = @Product AND SaleID <= @SaleID RETURN END GO The above function accepts the particular product for which we were searching, along with the SaleID from the SalesHistory table. From the function definition, you can see that the function returns a table named @SalesTable that contains two columns: SalesTotal and SalesCount. The body of the function inserts aggregate values into the @SalesTable table variable based upon the input parameters. The following code uses the APPLY operator to invoke the table-valued function with the values from the SalesHistory table. (Note: Logically, you may want to use a JOIN operator here, but it is not necessary. The APPLY operator essentially does the “JOIN” for us by applying the values from the SalesHistory table to the table-valued function. In a sense, this code works the same way a correlated sub-query does, except that it can return multiple correlated values.) SELECT * FROM SalesHistory sh CROSS APPLY dbo.udf_GetProductSalesTable(sh.Product, sh.SaleID) ORDER BY sh.SaleID ASC Additional TechRepublic resources on UDFs SQL Server 2000’s user-defined functions add flexibility, cut coding time Building and using table UDFs in SQL Server Incorporate SQL Server UDFs in your .NET applications http://www.techrepublic.com/blog/datacenter/understand-when-to-use-user-defined-functions-in-sql-server/171[08/29/2012 3:08:18 PM]
  • 4. Understand when to use user-defined functions in SQL Server | TechRepublic Tim Chapman is a SQL Server database administrator who works for a bank in Louisville, KY, and has more than 7 years of IT experience. He is also Microsoft certified in SQL Server 2000 and SQL Server 2005. If you would like to contact Tim, please e-mail him at chapman.tim@gmail.com. —————————————————————————————– Get SQL tips in your inbox TechRepublic’s free SQL Server newsletter, delivered each Tuesday, contains hands-on tips that will help you become more adept with this powerful relational database management system. Automatically subscribe today! Get IT Tips, news, and reviews delivered directly to your inbox by subscribing to TechRepublic’s free newsletters. About Tim Chapman Full Bio Contact Talking intelligently about Defragment your Windows virtualization Server 2003 hard drive on a set schedule 7 Join the conversation! Add Your Opinion Comments Follow via: Staff Picks Top Rated Most Recent My Contacts See All Comments UDF or View 0 pixelwiz 15th Jul 2011 Votes Can you please give some more details on when it is more appropriate to use a View vs a table-valued UDF? I have a few table-valued UDFs created that now I feel maybe should have been views, but I... Read Whole Comment + View in thread Scalar UDF in Where Clause 0 unclebiguns@... 13th Sep 2007 Votes So you are saying that if I use the a Scalar UDF ona variable or parameter in a where clause, it will not use an index? For example: Select product_id, product_name from products where... Read Whole Comment + View in thread RE: Understand when to use user-defined functions in 0 SQL Server Votes alaniane@... 7th Sep 2007 Thanks for the article on UDFs. I also like to use UDFs when designing queries. It http://www.techrepublic.com/blog/datacenter/understand-when-to-use-user-defined-functions-in-sql-server/171[08/29/2012 3:08:18 PM]
  • 5. Understand when to use user-defined functions in SQL Server | TechRepublic makes it easier to break complex queries into smaller chunks for debugging purposes. Later on, I will replace the... Read Whole Comment + View in thread See all comments Join the TechRepublic Community and join the conversation! Signing-up is free and quick, Do it now, we want to hear your opinion. Join Login http://www.techrepublic.com/blog/datacenter/understand-when-to-use-user-defined-functions-in-sql-server/171[08/29/2012 3:08:18 PM]