Functions vs Stored Procedures

后端 未结 12 639
我寻月下人不归
我寻月下人不归 2020-12-02 06:26

Let\'s say I have to implement a piece of T-SQL code that must return a table as result. I can implement a table-valued function or else a stored procedure that returns a se

12条回答
  •  暖寄归人
    2020-12-02 06:59

    As mentioned above, functions are more readable/composable/self documenting, but are less performant in general, and can be seriously less performant if you get carried away with them in joins such as

    SELECT *
    FROM dbo.tvfVeryLargeResultset1(@myVar1) tvf1
    INNER JOIN dbo.tvfVeryLargeResultset1(@myVar2) tvf2
        ON (tvf1.JoinId = tvf2.JoinId)
    

    Often, you just have to accept the redundancy of code that a tvf could eliminate (at a unacceptable performance cost.)

    One other point I haven't yet seen mentioned is that you can't use database state-changing temp tables inside of a multi-statement tvf. The most functionally equivalent mechanism to a temp table is the non-state changing, in memory table variable, and for large datasets, a temp table will likely be more performant than a table variable. (Other alternatives include dynamic tables & common table valued expressions, but at some level of complexity, these cease to be a good option IMO.)

提交回复
热议问题