Sql-server – Use Stored Procedure or View to return Data from Multiple Tables

sql serverstored-proceduresview

Is it just down to preference for whether to use a View or a stored procedure (or TVF) to simply return data joined from multiple base tables?

Is there any best practice regarding this? Should a stored procedure be used just for manipulating data? And is it best to use a view for the purpose of returning data from multiple tables?

Are there also likely to be any performance issues?

Query:

SELECT
    t.TagID, t.TagName, 
    t.IsActive AS 'IsTagActive',
    tk.TaskID, tk.TaskName,
    tk.IsActive AS 'IsTaskActive',
    g.GroupID, g.GroupName
FROM 
    Model.[Tag] t
INNER JOIN
    Model.[TagTaskMapping] ttm ON ttm.TagID = t.TagID
INNER JOIN  
    Model.[Task] tk ON tk.TaskID = ttm.TaskID
INNER JOIN
    Model.[Group] g ON g.GroupID = t.GroupID

Best Answer

A view is a good approach for when you need to flatten or consistently address how various base tables are organized, essentially de-normalizing the data for the consuming application. Your example includes tasks, tags and group information as a cohesive whole.

Alternatively, views can be used to restrict data consistently. For example if the definition of an "open" purchase order was complex then a view could streamline that.

Stored Procedures and Table Valued Functions are quite a bit different. They can accept arguments and include branching or more complex logic while still offering a simple interface for the client applications. Stored procedures can also modify data (logging tables) if needed.

I have also seen stored procedures used as a method to avoid parameter sniffing or getting better execution plans. A master stored procedure which determines whether to call sub-procedure 1 for a small amount of data or sub procedure 2 for a large amount of data.

Table Valued Functions are more similar to Stored Procedures than views and accept arguments, but can be used in joins. Their performance is generally terrible and should be used cautiously.