Published on

March 21, 2012

Exploring SQL Server: sp_describe_first_result_set

SQL Server is a powerful database management system that never ceases to amaze me. It offers a wide range of features and functionalities that make it a popular choice among developers and database administrators. One such feature that caught my attention recently is the sp_describe_first_result_set system stored procedure.

The sp_describe_first_result_set procedure does exactly what its name suggests – it describes the first result set of a given query. This can be incredibly useful when you need to understand the structure and metadata of the result set before executing the query.

Let’s take a look at a simple example:

EXEC sp_describe_first_result_set N'SELECT * FROM AdventureWorks.Sales.SalesOrderDetail', NULL, 1

This example will only work on SQL Server 2012. The procedure will provide a partial result set that describes the columns and their properties.

But the real power of sp_describe_first_result_set becomes evident when we use it with views. Let’s create a view called dbo.MyView:

USE AdventureWorks
GO

CREATE VIEW dbo.MyView AS
SELECT [SalesOrderID] soi_v, [SalesOrderDetailID] sodi_v, [CarrierTrackingNumber] stn_v
FROM [Sales].[SalesOrderDetail]
GO

Now, let’s execute the sp_describe_first_result_set procedure with various options:

EXEC sp_describe_first_result_set N'SELECT soi_v soi, sodi_v sodi, stn_v stn FROM MyView', NULL, 0
GO

EXEC sp_describe_first_result_set N'SELECT soi_v soi, sodi_v sodi, stn_v stn FROM MyView', NULL, 1
GO

EXEC sp_describe_first_result_set N'SELECT soi_v soi, sodi_v sodi, stn_v stn FROM MyView', NULL, 2
GO

By changing the last parameter, known as the browse_information_mode, we can observe different results. When set to 1, the result set describes the details of the original source database, schema, and table. When set to 2, the result set describes the details of the view as the source database.

I find it fascinating that SQL Server provides a system stored procedure that allows us to easily describe the result set of a query or view. This can be incredibly helpful when working with complex queries or views, as it provides valuable insights into the structure and metadata of the output.

Next time you find yourself needing to understand the result set of a query or view, give sp_describe_first_result_set a try. It might just save you time and effort in analyzing and understanding your data.

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.