Functions vs Stored Procedures

后端 未结 12 634
我寻月下人不归
我寻月下人不归 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:46

    I ran some tests with a long running bit of logic, with the same bit of code (a long SELECT statement) running in both a Table Valued Function and a Stored Procedure, and a straight EXEC/SELECT, and each performed identically.

    In my opinion always use a Table Valued Function rather than a stored procedure to return a result set, as it makes logic much easier and readable in queries that subsequently join to them, and enables you to reuse the same logic. To avoid too much of a performance hit, I often use "optional" parameters (i.e. you can pass NULL to them) to enable the function to return the result set to be quicker, e.g.:

    CREATE FUNCTION dbo.getSitePermissions(@RegionID int, @optPersonID int, optSiteID int)
    AS
    RETURN 
        SELECT DISTINCT SiteID, PersonID
        FROM dbo.SiteViewPermissions
        WHERE (@optPersonID IS NULL OR @optPersonID = PersonID)
        AND (@optSiteID IS NULL OR @optSiteID = SiteID)
        AND @RegionID = RegionID
    

    This way you can use this function for many different situations, and don't take a huge performance hit. I believe this is more efficient than filtering afterwards:

    SELECT * FROM dbo.getSitePermissions(@RegionID) WHERE SiteID = 1
    

    I have used this technique in several functions, sometimes with a long list of "optional" parameters of this type.

提交回复
热议问题