w3resource

Creating a Table-Valued Function with Joins


Create a Table-Valued Function with Joins

Write a SQL query to create a table-valued function that retrieves data using joins between multiple tables.

Solution:

-- Create a table-valued function with joins.
CREATE FUNCTION GetEmployeeDetailsByDepartment
    (@DepartmentID INT) -- Input parameter for the department ID.
RETURNS TABLE
AS
RETURN
    SELECT 
        E.EmployeeID,
        E.Name,
        E.Salary,
        D.DepartmentName
    FROM Employees E
    INNER JOIN Departments D ON E.DepartmentID = D.DepartmentID
    WHERE E.DepartmentID = @DepartmentID;

Explanation:

    1. Purpose of the Query :

    1. The goal is to create a table-valued function that retrieves employee details along with their department name by joining the Employees and Departments tables.

    2. Key Components :

    1. CREATE FUNCTION : Defines the table-valued function.
    2. INNER JOIN : Combines data from the Employees and Departments tables.
    3. RETURNS TABLE : Specifies that the function returns a table.

    3. Why Use Joins in Functions? :

    1. Functions with joins allow you to encapsulate complex queries into reusable components.

    4. Real-World Application :

    1. For example, in HR systems, you might use this function to generate reports showing employees grouped by department.

Additional Notes:

  • Table-valued functions are ideal for returning result sets that can be used in SELECT queries.
  • Use this exercise to teach how to integrate joins into reusable database logic.

For more Practice: Solve these Related Problems:

  • Write a SQL query to create a table-valued function that joins three tables and returns results filtered by a user-provided condition.
  • Write a SQL query to create a table-valued function that performs a self-join on a single table to find hierarchical relationships.
  • Write a SQL query to create a table-valued function that retrieves data from multiple tables using outer joins.
  • Write a SQL query to create a table-valued function that combines data from two tables using a cross join.


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous SQL Exercise: Create a Stored Procedure with Pagination.
Next SQL Exercise: Create a Trigger for Audit Logging.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.