SQL Server Functions

SQL Server Functions: Power and Best Practices

Hi everyone! Today we’re digging into functions in SQL Server. They’re great tools for wrapping up logic and reusing code, but, like everything in SQL, they need some care so they don’t turn into a performance bottleneck.

What Are Functions in SQL Server?

A function in SQL Server is a database object that takes input parameters, runs a set of actions (queries, calculations, and so on) and returns either a single value (scalar) or a table. They’re similar to stored procedures, with one crucial difference: functions can be used inside SELECT statements, WHERE, HAVING, and even inside other functions, which makes them extremely versatile.

There are two main kinds of functions we can create:

  1. Scalar Functions (Scalar-valued Functions - T-SQL): Return a single value of any data type.
  2. Table-valued Functions (TVFs): Return a table. They come in two flavors:
    • Inline Table-valued Functions (iTVFs): Simpler and faster, because they essentially expand the function’s logic straight into the calling query, like a parameterized view.
    • Multi-statement Table-valued Functions (mTVFs): Allow more complex logic, including multiple T-SQL statements, but can hurt performance significantly because of less aggressive optimizations and, often, the need to materialize data.

Why Use Functions?

  • Code Reuse: Write the logic once and use it in many places.
  • Modularity: Break complex problems into smaller, more manageable pieces.
  • Consistency: Make sure a specific business rule is applied the same way across the whole database.
  • Simpler Maintenance: Changes to the logic only need to be made in one place.

Creating Functions: Examples and Best Practices

Let’s look at some examples and, more importantly, the best practices!

1. Simple Scalar Function

Imagine you need to calculate the total tax on a price.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
CREATE FUNCTION dbo.CalcularImposto (@Preco DECIMAL(18, 2), @PercentualImposto DECIMAL(5, 2))
RETURNS DECIMAL(18, 2)
AS
BEGIN
    RETURN @Preco * (@PercentualImposto / 100);
END;
GO

-- Usage example
SELECT
    Produto,
    PrecoUnitario,
    dbo.CalcularImposto(PrecoUnitario, 10.00) AS ValorImposto,
    PrecoUnitario + dbo.CalcularImposto(PrecoUnitario, 10.00) AS PrecoTotal
FROM
    MinhaTabelaDeProdutos;

Performance Tip: Scalar functions, especially ones that do complex work or access data, can cause performance problems when called for every row of large result sets (the dreaded RBAR - Row By Agonizing Row). Ask yourself whether the logic could be handled directly in your main query, or whether an iTVF would be a better fit.

2. Table-valued Function (Inline TVF)

If you need to return a result set based on parameters, iTVFs are your best friends for performance. The query optimizer handles them very efficiently.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
CREATE FUNCTION dbo.ObterProdutosPorCategoria (@Categoria NVARCHAR(50))
RETURNS TABLE
AS
RETURN
(
    SELECT
        ProdutoID,
        NomeProduto,
        Preco
    FROM
        Produtos
    WHERE
        Categoria = @Categoria
);
GO

-- Usage example
SELECT
    p.ProdutoID,
    p.NomeProduto,
    p.Preco
FROM
    dbo.ObterProdutosPorCategoria('Eletrônicos') AS p
WHERE
    p.Preco > 500;

Why is an iTVF better than an mTVF in most cases? The query optimizer can “inline” (expand) the iTVF logic directly into the calling query, which allows broader optimizations and effective use of indexes. mTVFs, on the other hand, often materialize their results in a worktable, which can block good optimizations.

3. Table-valued Function (Multi-statement TVF) - Be Careful!

Although they’re useful for complex logic involving multiple steps or variables, mTVFs should be used with caution because of their potential impact on performance.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
-- CAREFUL: This is an mTVF example; usually avoid it if an iTVF is possible.
CREATE FUNCTION dbo.ObterRelatorioVendasMensal (@Ano INT, @Mes INT)
RETURNS @Relatorio TABLE
(
    ProdutoID INT,
    NomeProduto NVARCHAR(255),
    TotalVendas DECIMAL(18, 2),
    MediaVendasDiaria DECIMAL(18, 2)
)
AS
BEGIN
    INSERT INTO @Relatorio (ProdutoID, NomeProduto, TotalVendas)
    SELECT
        p.ProdutoID,
        p.NomeProduto,
        SUM(iv.Quantidade * iv.PrecoUnitario)
    FROM
        Produtos p
    INNER JOIN
        ItensVenda iv ON p.ProdutoID = iv.ProdutoID
    INNER JOIN
        Vendas v ON iv.VendaID = v.VendaID
    WHERE
        YEAR(v.DataVenda) = @Ano AND MONTH(v.DataVenda) = @Mes
    GROUP BY
        p.ProdutoID, p.NomeProduto;

    UPDATE @Relatorio
    SET MediaVendasDiaria = TotalVendas / DAY(EOMONTH(CAST(CAST(@Ano AS VARCHAR) + '-' + CAST(@Mes AS VARCHAR) + '-01' AS DATE)));

    RETURN;
END;
GO

-- Usage example
SELECT * FROM dbo.ObterRelatorioVendasMensal(2023, 7);

When should you use an mTVF? Only when the logic is truly complex and can’t be expressed concisely in an iTVF, and after considering other options such as views, CTEs or procedures that return results.

Essential Best Practices

  1. Avoid Scalar Functions on Columns of Large Tables in WHERE or JOIN Clauses: This prevents index use and forces a table scan. For example, WHERE dbo.MinhaFuncao(Coluna) = 'Valor' is a recipe for performance problems.
  2. Prefer iTVFs over mTVFs: Whenever possible, shape your logic to fit an Inline Table-valued Function so you benefit from SQL Server’s optimizations.
  3. Keep the Logic Simple: Overly complex functions become hard to debug and maintain, on top of potential performance issues.
  4. Use Proper Schemas: Always prefix your functions with the right schema (e.g., dbo.MinhaFuncao).
  5. Understand the Impact on Optimization: Functions can “hide” intent from the query optimizer, leading to suboptimal execution plans. Use SET STATISTICS IO ON and SET STATISTICS TIME ON, and analyze the execution plan to understand what’s going on.
  6. Test, Test, Test!: Test your functions with different data volumes and scenarios to make sure they perform well and return the expected results.

Functions are a core part of any SQL Server developer’s toolkit. Used correctly, they can greatly improve the efficiency and maintainability of your code. But remember: with great power comes great optimization responsibility!

Have you run into an interesting challenge with functions in SQL Server? Share your experience in the comments!

Built with Hugo
Theme Stack designed by Jimmy