Published on

June 25, 2008

Understanding Deferred Name Resolution in SQL Server

Have you ever wondered why a stored procedure (SP) can be created successfully even if there is an incorrect table name, but it fails to create if there is an incorrect column name? This concept is known as Deferred Name Resolution in SQL Server.

When a stored procedure is created, it undergoes a syntactical check. If there are no errors, the text of the stored procedure is stored in the sys.sql_module catalog. However, if there is an error, the stored procedure is not created and no entry is made in the sys.sql_module catalog.

Deferred Name Resolution comes into play when the stored procedure is executed for the first time. At this point, SQL Server checks for all the objects used in the stored procedure statement. If there is a table that does not exist in the database, a runtime error is thrown. However, if there is a misspelled column name in an existing table, the stored procedure creation is not allowed.

Let’s understand this with an example:

USE AdventureWorks
GO

CREATE PROCEDURE usp_TestDeferred
AS
SELECT FirstName FROM Projects
GO

In the above example, the table “Projects” does not exist in the AdventureWorks database. However, the stored procedure is created without any error. This is because the syntactical check is successful, and the text of the stored procedure is stored in the sys.sql_module catalog.

USE AdventureWorks
GO

CREATE PROCEDURE sp_Employee
AS
SELECT UserName FROM Employees
GO

In this example, the table “Employees” exists in the AdventureWorks database, but there is no column named “UserName”. Therefore, the stored procedure creation fails and an error is thrown.

If a stored procedure encounters a missing object during execution, it stops execution at that point and throws an error.

Understanding Deferred Name Resolution is important as it helps in identifying potential errors in your SQL code. By ensuring that all table and column names are correct, you can avoid runtime errors and improve the overall performance of your SQL Server.

What are your thoughts on this topic? Do you have any interesting questions related to SQL Server concepts? I encourage you to share your thoughts and questions in the comments section below.

Click to rate this post!
[Total: 0 Average: 0]

Let's work together

Send us a message or book free introductory meeting with us using button below.