I'm currently learning about functions in sql server and I don't understand why/when you would use an inline table valued function.
I've tried reading about it and some examples but it is still unclear to me. Can someone explain or provide an easy to understand use-case scenario?
Table-valued functions are "just" parameterized views. This makes them extremely powerful for encapsulating logic that would otherwise be hidden behind an opaque stored procedure. Here's an example:
Inline Table-valued Function:
Stored Procedure:
Unlike the stored procedure call, a table-valued function allows me to compose the logic from
dbo.GetClients
with other objects:In such situations I cannot imagine using a stored procedure because of how restrictive it is when compared to the table-valued function. I would be forced to marshal the data around myself using a temp table, table variable, or application layer in order to combine results from multiple objects.
Inline table-valued functions are especially awesome because of the "inline" bit which is probably best explained here. This allows the optimizer to treat such functions no differently than the objects they encapsulate, resulting in near optimal performance plans (assuming that your indexes and statistics are ideal).
This is a great question and a topic that's not discussed enough IMHO. Think of inline table valued functions as views that accept parameters. That's the short answer but let's dig a little deeper...
In SQL server you have three kinds of user-defined functions*: scalar functions (svf), multi-line table valued functions (mTVF) and inline table valued functions (iTVF). svfs return a single value, both mTVFs and iTVFs return a table. The difference between mTVFs and iTVFs is performance. In short - mTVFs are slow, iTVFs can be (and almost always are) much faster. mTVFs allow you to do things you couldn't do in a view (e.g. create temp tables, perform loops, utilize cursors...), iTVFs, again, have the same restrictions as views except for they can except parameters.
I use iTFVs for common data warehouse queries where I need a view that takes parameter and splitting/manipulating strings. A more advanced use of iTVFs which has changed my career is replacing scalar functions with iTVFs - see this article from Jeff Moden titled, "How to Make Scalar UDFs Run Faster": http://www.sqlservercentral.com/articles/T-SQL/91724/