SQL Server User-Defined Functions, Temp Tables and Table Variables Explained

SQL Server 7 min readUpdated Nov 20, 2026
8 views0 comments

Good T-SQL reuses its logic and breaks big problems into small steps. This guide shows how to create your own functions (scalar and table-valued), how to use CROSS APPLY, and how to keep intermediate results in temp tables and table variables, with advice on which one to choose.

Part of the SQL Server for Beginners series. This article is the written version of lesson 9 of the Bigland Network video course, with the same sample data. The results shown were worked out by hand from that data, so run every example on a test database, not on production data.

Watch lesson 9 as a video or open it on YouTube. The written lesson below follows the same steps and the same sample data.


Contents

1. Why reuse logic?

  • A function lets you write a calculation once and use it in many queries.
  • A temp table keeps an intermediate result so you can build a complex query step by step.
  • A table variable does the same for a small result.
  • Temporary objects live in the tempdb database, and SQL Server cleans them up for you.

2. Scalar functions

A scalar function returns exactly one value. This one returns a ten percent bonus:

CREATE FUNCTION dbo.Bonus (@salary DECIMAL(10,2))
RETURNS DECIMAL(10,2)
AS
BEGIN
    RETURN @salary * 0.10;
END;

Call it with the schema name (dbo.Bonus), like a built-in function:

SELECT FirstName, Salary, dbo.Bonus(Salary) AS Bonus
FROM Employees ORDER BY Id;
FirstName Salary Bonus
Amina 4200 420.00
Youssef 5200 520.00
Salma 3600 360.00
Karim 3100 310.00
Nadia 4800 480.00
Omar 3900 390.00

You can also use it in WHERE: WHERE dbo.Bonus(Salary) > 400 returns Amina (420), Youssef (520) and Nadia (480). It works, but SQL Server calls the function for every row, which can be slow on big tables.

3. Table-valued functions and CROSS APPLY

An inline table-valued function returns a table from a single SELECT. There is no BEGIN or END, and it is the fastest kind:

CREATE FUNCTION dbo.EmpByDept (@DeptId INT)
RETURNS TABLE
AS
RETURN (
    SELECT FirstName, Salary
    FROM Employees
    WHERE DeptId = @DeptId
);

Because it returns a table you call it in the FROM clause. Think of it as a view that takes a parameter:

SELECT * FROM dbo.EmpByDept(2)
ORDER BY Salary DESC;
FirstName Salary
Youssef 5200
Nadia 4800

To run the function once for every row of another table, use CROSS APPLY:

SELECT d.DeptName, f.FirstName
FROM Departments d
CROSS APPLY dbo.EmpByDept(d.DeptId) f
ORDER BY d.DeptId, f.FirstName;
DeptName FirstName
Sales Amina
Sales Salma
IT Nadia
IT Youssef
HR Karim

Finance has no employees, so it disappears. OUTER APPLY keeps it with empty values.

Kind Notes
Scalar Returns one value. Simple, but can be slow on big tables.
Inline table-valued Returns a table from one SELECT. Fast. Best choice.
Multi-statement table-valued Builds its table step by step. Often slower.
Rule for all A function cannot change data in your tables.

Change or remove a function

CREATE OR ALTER FUNCTION dbo.Bonus (@salary DECIMAL(10,2))
RETURNS DECIMAL(10,2)
AS
BEGIN RETURN @salary * 0.12; END;
GO
DROP FUNCTION IF EXISTS dbo.Bonus;

CREATE OR ALTER keeps permissions. CREATE FUNCTION must be the first statement in its batch, which is why the examples use GO.

4. Temporary tables

  • #Name is local: only your session can see it.
  • ##Name is global: every session can see it.
  • They live in tempdb, can have indexes and statistics like real tables, and are dropped automatically when the session ends.

The quickest way to create one is SELECT ... INTO:

SELECT FirstName, Salary
INTO #HighPaid
FROM Employees
WHERE Salary >= 4000;

SELECT * FROM #HighPaid ORDER BY Salary DESC;
FirstName Salary
Youssef 5200
Nadia 4800
Amina 4200

Or create it yourself and fill it with INSERT:

CREATE TABLE #Bonus (EmpId INT, Amount DECIMAL(10,2));

INSERT INTO #Bonus
SELECT Id, Salary * 0.05
FROM Employees WHERE DeptId = 1;

SELECT * FROM #Bonus;
EmpId Amount
1 210.00
3 180.00

A temp table is used like any table: JOIN, UPDATE, DELETE and indexes all work.

SELECT e.FirstName, b.Amount
FROM Employees e
JOIN #Bonus b ON e.Id = b.EmpId
ORDER BY e.Id;
FirstName Amount
Amina 210.00
Salma 180.00

Clean up with DROP TABLE IF EXISTS #HighPaid;. It frees tempdb space and lets you re-run your script without an error.

5. Table variables

DECLARE @Top TABLE (Id INT, Name VARCHAR(20));

INSERT INTO @Top
SELECT TOP 3 Id, FirstName FROM Employees
ORDER BY Salary DESC;

SELECT * FROM @Top ORDER BY Id;
Id Name
1 Amina
2 Youssef
5 Nadia

There is no CREATE and no DROP: the variable disappears at the end of the batch.

Temp table, table variable or CTE?

Choice Best for
#Temp table Bigger data, indexes and statistics, reuse across several batches in a session.
@Table variable Small lists, lives only until the batch ends. It ignores a ROLLBACK; a temp table does not.
CTE A single statement; nothing is stored (see <a href=”/sql-server-cte-window-functions-beginners/”>Lesson 7: CTEs and Window Functions</a>).

6. Putting it together

Store each department’s average salary in a temp table, then find employees who earn more than their department average:

SELECT DeptId, AVG(Salary) AS AvgSal INTO #DeptAvg
FROM Employees WHERE DeptId IS NOT NULL GROUP BY DeptId;

SELECT e.FirstName, e.Salary, a.AvgSal
FROM Employees e JOIN #DeptAvg a ON e.DeptId = a.DeptId
WHERE e.Salary > a.AvgSal ORDER BY e.Id;
FirstName Salary AvgSal
Amina 4200 3900
Youssef 5200 5000

7. Common mistakes and best practices

  • Calling a scalar function without the schema name.
  • Using a scalar function on a huge table: it runs row by row (How to Find and Fix Slow Queries in SQL Server).
  • Forgetting to drop a temp table and getting an error when the script runs again.
  • Using a table variable for thousands of rows.
  • Using a global ## table by accident: other sessions can see it.
  • Best practice: prefer inline table functions to scalar ones, start scripts with DROP TABLE IF EXISTS, use temp tables for big or reused results, table variables for small lists, and choose clear names such as dbo.Bonus and #HighPaid.

8. Practice

  • Create dbo.AnnualSalary that multiplies a monthly salary by 12 and show each name with it.
  • Put the Sales employees (department 1) in a temp table, then sum their salaries.
  • Put the IT employees in a table variable and list them by name.
CREATE FUNCTION dbo.AnnualSalary (@m INT)
RETURNS INT AS BEGIN RETURN @m * 12; END;
GO
SELECT FirstName, dbo.AnnualSalary(Salary) AS Annual
FROM Employees ORDER BY Id;

Annual salaries: Amina 50400, Youssef 62400, Salma 43200, Karim 37200, Nadia 57600 and Omar 46800.

SELECT FirstName, Salary INTO #SalesTeam
FROM Employees WHERE DeptId = 1;
SELECT SUM(Salary) AS Total FROM #SalesTeam;    -- 7800

DECLARE @It TABLE (Name VARCHAR(20), Salary INT);
INSERT INTO @It SELECT FirstName, Salary FROM Employees WHERE DeptId = 2;
SELECT * FROM @It ORDER BY Name;               -- Nadia 4800, Youssef 5200

Frequently asked questions

Are scalar functions bad for performance?

On large tables they can be, because they run once per row and can prevent parallelism. Prefer an inline table-valued function or plain SQL when performance matters.

Do temp tables slow down tempdb?

They use tempdb space, so drop them when you are done and avoid very large temp tables on a busy server.

Can a function change data?

No. A function cannot modify the data in your tables. Use a stored procedure (Lesson 6: Indexes, Views and Stored Procedures) for that.

What to learn next

The next lesson, Lesson 10: Triggers and Audit Tables, is out now. After it we cover security, backup and restore, and performance tuning. Meanwhile, see SQL Server Agent Jobs and How to Back Up and Restore a SQL Server Database with T-SQL. Previous lesson: Lesson 8: Built-in Functions.

The whole series

Sources and further reading

  • Microsoft Learn, Transact-SQL reference (Database Engine), on learn.microsoft.com: the official syntax for every statement used here.
  • Microsoft Learn, SQL Server documentation, for SQL Server Management Studio (SSMS) and the sample concepts.
Did you find this helpful?Tap the heart to let us know. It takes one second and no account.

More tutorials like this

Leave a Comment

Your email address will not be published. Required fields are marked *

Bigland Network IT

Practical tutorials for people who run, build and fix things: operating systems, databases, development, networking and security.

Topics

More

Site

© 2026 Bigland Network. All rights reserved.Always test commands on a non-production system first.
Scroll to Top