Views Stored Procedures and Functions
Earn 25 points (50 with Pro) in two steps
- ① Read through the lesson — each section gets a ✓ as you scroll through it.
- ② When every section has a ✓, tap Complete lesson.
0 of 10 read · keep scrolling
✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro
Mastering Database Programmability: Views, Stored Procedures, and Functions on Azure SQL
Introduction: The Architecture of Database Logic
When we talk about relational databases on Azure, we are not just talking about storing rows and columns of data. We are talking about building a system that can process, secure, and retrieve that data efficiently. If your database is a library, the tables are the shelves where the books live. However, you don't want every patron walking into the stacks to move the books around, reorganize them, or accidentally tear pages out. You want a system where they can ask for specific information, follow a set process to check out a book, or receive a summary of the library's inventory.
This is where Views, Stored Procedures, and User-Defined Functions (UDFs) come into play. These three objects form the core of database programmability. They allow you to abstract the complexity of your underlying table structures, enforce business rules directly at the data layer, and improve the performance of your applications. By moving logic into the database, you ensure that no matter which application—be it a web app, a mobile app, or a data analytics tool—accesses your data, the rules remain consistent and the performance remains optimized.
In this lesson, we will dive deep into these three constructs. We will explore how to create them, when to use them, and the specific nuances of working with them within the Azure SQL ecosystem. Whether you are managing an Azure SQL Database or an Azure SQL Managed Instance, the principles remain the same.
Not read yet
Part 1: Views – The Virtual Window into Your Data
A view is essentially a saved SELECT statement. When you query a view, SQL Server executes the underlying query and presents the result set as if it were a physical table. Views are incredibly powerful because they allow you to hide the complexity of joins, filter out sensitive columns, or present data in a format that is easier for developers to consume.
Why Use Views?
There are three primary reasons to implement views in your Azure SQL environment:
- Security and Access Control: You can grant a user permission to select from a view without giving them direct access to the underlying tables. This allows you to hide columns containing personally identifiable information (PII) like social security numbers or salaries while still letting the user see the rest of the record.
- Simplification: If you have a complex report that requires joining five different tables, you can create a view that performs the join once. Developers can then simply run
SELECT * FROM MyComplexReportViewinstead of rewriting the join logic every time. - Logical Data Independence: If you decide to rename a column in your underlying table, you can update the view to map the old name to the new column name. This prevents your application code from breaking because the view acts as a contract between the database schema and the application.
Creating and Modifying Views
Creating a view is straightforward. You use the CREATE VIEW statement followed by the AS keyword and your query.
CREATE VIEW dbo.vw_CustomerOrders AS
SELECT
c.CustomerID,
c.FirstName,
c.LastName,
o.OrderID,
o.OrderDate,
o.TotalAmount
FROM dbo.Customers c
JOIN dbo.Orders o ON c.CustomerID = o.CustomerID
WHERE o.OrderDate >= '2023-01-01';
Once this view is created, you can query it just like a table: SELECT * FROM dbo.vw_CustomerOrders. If you need to change the logic of the view later, you don't need to drop it; you simply use ALTER VIEW to update the definition.
Callout: Views vs. Tables A common misconception is that views store data. They do not. A standard view is a "virtual" table. Every time you query a view, the database engine compiles the query and fetches the data from the underlying tables at that moment. The only exception is an Indexed View, where the result set is physically stored on disk, which can significantly speed up performance for complex aggregations but carries overhead for updates.
Best Practices for Views
- Always use schema names (e.g.,
dbo.) to avoid ambiguity. - Avoid using
SELECT *inside a view definition. Explicitly list the columns you need. This prevents the view from breaking if a column is added or removed from the base table. - Keep the logic inside the view focused. Do not try to perform massive data transformations; keep it clean and performant.
Not read yet
Part 2: Stored Procedures – Automating Complex Workflows
If a view is a window, a stored procedure is a machine. A stored procedure is a collection of T-SQL statements that are compiled and stored in the database. Unlike a view, which is meant to be queried, a stored procedure is meant to be executed. It can perform multiple operations, including data modification (INSERT, UPDATE, DELETE), looping, conditional logic, and error handling.
The Power of Stored Procedures
Stored procedures are the primary way to encapsulate business logic in Azure SQL. By using them, you reduce the amount of data transferred between your application and the database. Instead of sending five separate update commands from your web server, you send one call to a stored procedure, which executes those five commands internally on the server.
Example: Processing an Order
Let's look at how you might write a stored procedure to handle an order entry process.
CREATE PROCEDURE dbo.usp_PlaceOrder
@CustomerID INT,
@ProductID INT,
@Quantity INT
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
BEGIN TRANSACTION;
-- Check inventory
IF (SELECT StockLevel FROM dbo.Products WHERE ProductID = @ProductID) >= @Quantity
BEGIN
-- Reduce inventory
UPDATE dbo.Products
SET StockLevel = StockLevel - @Quantity
WHERE ProductID = @ProductID;
-- Insert the order
INSERT INTO dbo.Orders (CustomerID, ProductID, Quantity, OrderDate)
VALUES (@CustomerID, @ProductID, @Quantity, GETDATE());
COMMIT TRANSACTION;
END
ELSE
BEGIN
RAISERROR('Insufficient stock.', 16, 1);
ROLLBACK TRANSACTION;
END
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION;
-- Log error here
THROW;
END CATCH
END;
Key Features of Stored Procedures
- Parameters: You can pass input values (like
CustomerIDorQuantity) into the procedure. - Transactions: You can wrap multiple statements in a transaction, ensuring that either all statements succeed or none do (atomicity).
- Security: You can grant users
EXECUTEpermissions on a procedure without giving themINSERTorUPDATEpermissions on the underlying tables. - Performance: The first time a stored procedure is executed, SQL Server creates an execution plan and caches it. Subsequent executions use this cached plan, which is faster than re-compiling the query every time.
Note: Always use
SET NOCOUNT ON;at the start of your stored procedures. This prevents the database from sending "DoneInProc" messages for every single statement inside the procedure, which reduces network traffic and slightly improves performance.
Not read yet
Part 3: User-Defined Functions (UDFs) – Extending T-SQL
User-Defined Functions (UDFs) are routines that accept parameters, perform an action, and return a result. They are similar to stored procedures in that they contain T-SQL code, but they are fundamentally different in their usage and limitations.
Scalar vs. Table-Valued Functions
There are two main types of functions you will work with:
- Scalar Functions: These return a single value (like an integer, a string, or a date). They are often used in
SELECTlists orWHEREclauses.- Example: A function that calculates the tax on an order total.
- Table-Valued Functions (TVFs): These return a table as the result. They are incredibly powerful because they can be used in a
FROMclause just like a table or a view.- Example: A function that returns a list of all orders for a specific customer.
Creating a Table-Valued Function
CREATE FUNCTION dbo.fn_GetCustomerOrders (@CustomerID INT)
RETURNS TABLE
AS
RETURN (
SELECT OrderID, OrderDate, TotalAmount
FROM dbo.Orders
WHERE CustomerID = @CustomerID
);
You can then query this function like this:
SELECT * FROM dbo.fn_GetCustomerOrders(123);
Important Constraints on Functions
- Side Effects: Functions are not allowed to have "side effects." This means you cannot perform
INSERT,UPDATE, orDELETEoperations on permanent tables inside a function. You cannot use functions to change the state of the database. - Error Handling: Unlike stored procedures, you cannot use
TRY...CATCHblocks inside a function. - Performance: Scalar functions can often cause performance issues if used in the
SELECTlist of a query that processes millions of rows. This is because the function is executed once for every single row in the result set (a phenomenon known as "row-by-row" processing).
Not read yet
Part 4: Comparing Database Objects
To help you decide which tool to use for a specific problem, refer to the following comparison table:
| Feature | View | Stored Procedure | User-Defined Function |
|---|---|---|---|
| Returns | Result set | Result set, status, or params | Scalar value or table |
| Can Modify Data? | No | Yes | No |
| Can use Transactions? | No | Yes | No |
| Can be used in JOIN? | Yes | No | Yes (TVF only) |
| Main Purpose | Simplification/Security | Workflow/Logic | Reusable calculations |
Part 5: Best Practices and Industry Standards
Working in Azure SQL requires a disciplined approach to development. Because the database is often a shared resource, poor code quality can impact not just one application, but the entire ecosystem.
Managing Schema Changes
Always use source control (like GitHub or Azure DevOps) for your database code. Never make changes directly in the production Azure SQL portal. Instead, develop locally or in a development environment, script your changes into migration files, and deploy them using CI/CD pipelines. This ensures that your view, procedure, and function definitions are versioned and can be rolled back if an error occurs.
Avoiding Common Pitfalls
- The "N+1" Problem with Scalar Functions: If you have a query that selects 10,000 customers and you call a scalar function
dbo.fn_GetCustomerAge(BirthDate)for each row, the engine has to execute that function 10,000 times. This will kill your query performance. Instead, try to perform the calculation using standard T-SQL math or a join. - Overusing Cursors: Cursors are notoriously slow in SQL Server because they process data row-by-row. Always look for set-based solutions (using
JOINs,UPDATEstatements, orCTEs) before resorting to a cursor inside a stored procedure. - Lack of Input Validation: Always validate your parameters inside stored procedures. If a procedure expects an ID that is greater than 0, check that at the beginning of the procedure and raise an error if it is invalid. This prevents corrupted data from entering your system.
Warning: Dynamic SQL Risks You may be tempted to use dynamic SQL (
EXEC sp_executesql) inside procedures to build flexible queries. While powerful, this introduces the risk of SQL Injection if you concatenate user input directly into the query string. Always usesp_executesqlwith properly defined parameters to prevent malicious code injection. Never useEXEC(@string)with concatenated user input.
Step-by-Step: Refactoring for Performance
If you find that a stored procedure is running slowly, follow these steps to troubleshoot:
- Execution Plan Analysis: Open SQL Server Management Studio (SSMS) or Azure Data Studio, turn on the "Include Actual Execution Plan" option, and run your procedure.
- Identify Bottlenecks: Look for "Table Scans" or "Index Scans" in the execution plan. These indicate that the database is reading the entire table instead of using an index.
- Optimize Indexes: Ensure the columns used in your
WHEREclauses andJOINconditions are indexed appropriately. - Parameter Sniffing: Sometimes, the execution plan chosen for one set of parameters is bad for another. If you suspect this, try using
OPTION (RECOMPILE)on specific queries inside the procedure to force the engine to generate a fresh plan based on the current parameters.
Not read yet
Part 6: Deep Dive into Security Models
In an Azure SQL environment, security is paramount. You should follow the "Principle of Least Privilege" when implementing these objects.
Module Signing and Execution Context
One of the most advanced and secure ways to use stored procedures is through Execution Context. You can define a stored procedure to run as a specific user, even if the person executing it doesn't have permissions to the underlying tables.
CREATE PROCEDURE dbo.usp_SecureUpdate
WITH EXECUTE AS OWNER
AS
BEGIN
UPDATE dbo.FinancialData SET Status = 'Verified';
END;
In this example, if the database owner has permission to update FinancialData, any user granted EXECUTE permission on this procedure can trigger the update. They do not need direct access to the FinancialData table. This is a powerful way to expose specific functionality without exposing the underlying data structure.
Granting Permissions
Once your objects are created, you must manage access. Do not grant broad permissions like db_datareader or db_datawriter. Instead, grant granular access:
-- Granting access to a view
GRANT SELECT ON dbo.vw_CustomerOrders TO SalesRole;
-- Granting access to a procedure
GRANT EXECUTE ON dbo.usp_PlaceOrder TO OrderEntryRole;
Not read yet
Part 7: Handling Errors Effectively
In a production system, things will inevitably go wrong. A network glitch might interrupt a transaction, or a constraint might be violated. Your stored procedures must handle these cases gracefully.
The Try-Catch Pattern
As shown in the earlier example, wrapping your logic in BEGIN TRY...BEGIN CATCH is essential. Inside the CATCH block, you should use the following functions to capture details:
ERROR_NUMBER(): Returns the ID of the error.ERROR_MESSAGE(): Provides the text description of the error.ERROR_SEVERITY(): Indicates the severity level.
Logging these errors to a dedicated ErrorLog table is a best practice that allows you to monitor the health of your database processes over time.
BEGIN CATCH
INSERT INTO dbo.ErrorLog (ErrorNumber, ErrorMessage, ErrorTime)
VALUES (ERROR_NUMBER(), ERROR_MESSAGE(), GETDATE());
-- Re-throw the error so the application knows it failed
THROW;
END CATCH
Not read yet
Part 8: Advanced Concepts – When to use what?
As you grow in your database development journey, you will encounter scenarios where the choice between these objects becomes nuanced.
The Case for Indexed Views
If you have a massive dataset and you frequently need to aggregate data (like calculating the total sales per region), a standard view will be slow because it calculates the total every time. An Indexed View stores the result of the view on disk. When you add a new row to the base table, the database automatically updates the index. This is a trade-off: you get lightning-fast reads, but your INSERT and UPDATE operations on the base tables become slightly slower because the index must be maintained.
The Case for Inline TVFs vs. Multi-Statement TVFs
There are two types of Table-Valued Functions. An Inline TVF consists of a single SELECT statement. The SQL optimizer treats an Inline TVF exactly like a view—it "expands" the query into the main execution plan, allowing for full optimization. A Multi-Statement TVF uses a BEGIN...END block and populates a table variable. These are often treated as "black boxes" by the optimizer, meaning they can lead to poor performance because the engine cannot see what is happening inside. Always prefer Inline TVFs whenever possible.
Not read yet
Quick Reference: Syntax Cheat Sheet
| Object | Basic Creation Syntax | Key Characteristic |
|---|---|---|
| View | CREATE VIEW Name AS SELECT... |
Virtual table, no parameters |
| Stored Proc | CREATE PROC Name @Param INT AS BEGIN... |
Procedural logic, can modify data |
| Scalar UDF | CREATE FUNCTION Name (@P INT) RETURNS INT AS BEGIN... |
Returns one value, use in SELECT |
| Inline TVF | CREATE FUNCTION Name (@P INT) RETURNS TABLE AS RETURN (SELECT...) |
Returns table, highly performant |
Common Questions (FAQ)
Q: Can I use a Stored Procedure inside a View? A: No, you cannot. A view must be a single deterministic query. A stored procedure can perform multiple tasks and modify data, which violates the requirements of a view.
Q: What is the difference between a local temporary table and a table variable inside a procedure?
A: Local temporary tables (#Table) are physically created in tempdb and support indexes, which can make them faster for large datasets. Table variables (@Table) are memory-resident and do not support statistics or indexes, making them better for small sets of data.
Q: Should I use NOLOCK in my views to make them faster?
A: Be very careful with NOLOCK. While it prevents your query from waiting on other processes, it allows "dirty reads," meaning you might see data that is currently being changed and might never be committed. Only use NOLOCK if you are okay with potentially inaccurate data for the sake of speed.
Not read yet
Key Takeaways
- Abstraction is Key: Use Views to provide a simple, secure, and stable interface for your applications. Never expose raw tables to end-users or external applications if you can avoid it.
- Logic Belongs in Procedures: Move your complex business logic into Stored Procedures. This centralizes your rules, reduces network traffic, and improves performance through cached execution plans.
- Functions for Calculations: Use User-Defined Functions (specifically Inline TVFs) for reusable logic and calculations, but be cautious with scalar functions in large queries to avoid the performance trap of row-by-row processing.
- Prioritize Set-Based Operations: Always prefer operations that handle sets of data at once (JOINs, UPDATEs) over cursors or row-by-row iteration.
- Security First: Utilize
EXECUTE ASand granularGRANTpermissions to ensure that users can only perform the actions they absolutely need, following the principle of least privilege. - Error Handling is Non-Negotiable: Always include
TRY...CATCHblocks in your stored procedures to ensure that your database can recover gracefully from errors and log incidents for future investigation. - Version Control: Database code is still code. Treat your views, procedures, and functions as source code, checking them into your version control system to maintain a history of changes and facilitate safe deployments.
By mastering these three building blocks, you transition from simply storing data to creating a robust, performant, and secure data platform in Azure. The database is not just a storage bin; it is an active participant in your application's logic. Use these tools wisely, and you will build systems that are easier to maintain, faster to execute, and safer to operate.
Not read yet
Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.
- Understanding Structured Data
- Understanding Structured Data Quiz5q
- Features of Structured Data
- Features of Structured Data Quiz5q
- Semi-Structured Data Concepts
- Semi-Structured Data Concepts Quiz5q
- Features of Semi-Structured Data
- Features of Semi-Structured Data Quiz5q
- Understanding Unstructured Data
- Understanding Unstructured Data Quiz5q
- Features of Unstructured Data
- Features of Unstructured Data Quiz5q
- Transactional Workloads Overview
- Transactional Workloads Overview Quiz5q
- Features of Transactional Workloads
- Features of Transactional Workloads Quiz5q
- OLTP Systems
- OLTP Systems Quiz5q
- Analytical Workloads Overview
- Analytical Workloads Overview Quiz5q
- Features of Analytical Workloads
- Features of Analytical Workloads Quiz5q
- OLAP Systems
- OLAP Systems Quiz5q
- SQL Statement Types
- SQL Statement Types Quiz5q
- SELECT Statement Basics
- SELECT Statement Basics Quiz5q
- INSERT UPDATE DELETE Statements
- INSERT UPDATE DELETE Statements Quiz5q
- Common Database Objects
- Common Database Objects Quiz5q
- Views Stored Procedures and Functions
- Views Stored Procedures and Functions Quiz5q
- JOIN Operations
- JOIN Operations Quiz5q
- Azure SQL Family Overview
- Azure SQL Family Overview Quiz5q
- Azure SQL Database
- Azure SQL Database Quiz5q
- Azure SQL Managed Instance
- Azure SQL Managed Instance Quiz5q
- SQL Server on Azure VMs
- SQL Server on Azure VMs Quiz5q
- Azure Database for MySQL
- Azure Database for MySQL Quiz5q
- Azure Database for PostgreSQL
- Azure Database for PostgreSQL Quiz5q
- Azure Database for MariaDB
- Azure Database for MariaDB Quiz5q
- Azure Cosmos DB Overview
- Azure Cosmos DB Overview Quiz5q
- Cosmos DB Use Cases
- Cosmos DB Use Cases Quiz5q
- Cosmos DB APIs Overview
- Cosmos DB APIs Overview Quiz5q
- Cosmos DB for NoSQL
- Cosmos DB for NoSQL Quiz5q
- Cosmos DB for MongoDB
- Cosmos DB for MongoDB Quiz5q
- Cosmos DB for Apache Cassandra
- Cosmos DB for Apache Cassandra Quiz5q
- Cosmos DB for Apache Gremlin
- Cosmos DB for Apache Gremlin Quiz5q
- Cosmos DB for Table
- Cosmos DB for Table Quiz5q
- Global Distribution in Cosmos DB
- Global Distribution in Cosmos DB Quiz5q
- Data Ingestion Concepts
- Data Ingestion Concepts Quiz5q
- Data Processing Considerations
- Data Processing Considerations Quiz5q
- Analytical Data Stores
- Analytical Data Stores Quiz5q
- Data Warehouses and Data Lakes
- Data Warehouses and Data Lakes Quiz5q
- Azure Databricks Overview
- Azure Databricks Overview Quiz5q
- Microsoft Fabric Overview
- Microsoft Fabric Overview Quiz5q
- Azure Synapse Analytics
- Azure Synapse Analytics Quiz5q
- Azure Data Factory
- Azure Data Factory Quiz5q
- Power BI Overview
- Power BI Overview Quiz5q
- Power BI Capabilities
- Power BI Capabilities Quiz5q
- Power BI Data Models
- Power BI Data Models Quiz5q
- Data Model Features
- Data Model Features Quiz5q
- Power BI Visualizations
- Power BI Visualizations Quiz5q
- Choosing Appropriate Visualizations
- Choosing Appropriate Visualizations Quiz5q
- Reports and Dashboards
- Reports and Dashboards Quiz5q
- Power BI Desktop vs Service
- Power BI Desktop vs Service Quiz5q
- Data Refresh and Gateways
- Data Refresh and Gateways Quiz5q
Spend your points to unlock exam-style practice questions
Spend points to unlock DP-900 exam-style practice questions.
Practice for DP-900