Database Function VS Case Statement

前端 未结 3 1245
萌比男神i
萌比男神i 2021-02-20 14:11

Yesterday we got a scenario where had to get type of a db field and on base of that we had to write the description of the field. Like

Select ( Cas         


        
相关标签:
3条回答
  • 2021-02-20 14:38

    When using a scalar function (a function that returns one value) the contents of the function will be executed once per row but the case statement will be executed across the entire set.

    By operating against the entire set you allow the server to optimise your query more efficiently.

    So the theory goes that the same query run both ways against a large dataset then the function should be slower. However, the difference may be trivial when operating against your data so you should try both methods and test them to determine if any performance trade off is worth the increased utility of a function.

    0 讨论(0)
  • 2021-02-20 14:47
    UDF function is always slower than case statements
    

    Please refer the article

    http://blogs.msdn.com/b/sqlserverfaq/archive/2009/10/06/performance-benefits-of-using-expression-over-user-defined-functions.aspx

    The following article suggests you when to use UDF

    http://www.sql-server-performance.com/2005/sql-server-udfs/

    Summary :

    There is a large performance penalty paid when User defined functions is used.This penalty shows up as poor query execution time when a query applies a UDF to a large number of rows, typically 1000 or more. The penalty is incurred because the SQL Server database engine must create its own internal cursor like processing. It must invoke each UDF on each row. If the UDF is used in the WHERE clause, this may happen as part of the filtering the rows. If the UDF is used in the select list, this happens when creating the results of the query to pass to the next stage of query processing. It's the row by row processing that slows SQL Server the most.

    0 讨论(0)
  • 2021-02-20 14:51

    Your devolper is right. Functions will slow down your query.

    https://sqlserverfast.com/?s=user+defined+ugly

    Calling functionsis like:
    wrap parts into paper
    put it into a bag
    carry it to the mechanics
    let him unwrap, do something, wrapt then result
    carry it back
    use it
    
    0 讨论(0)
提交回复
热议问题