Published on

January 30, 2022

Using Stored Procedures in SELECT Statements – SQL Server

One of the common questions I often receive is about how to use stored procedures in SELECT statements. There are several methods to achieve this, but today we will focus on the easiest way. Let’s dive in!

There are various ways to get the results of a stored procedure in a SELECT statement, such as creating a temp table, using table variables, or even using functions. However, the easiest method involves using the OPENROWSET function to execute the stored procedure within the SELECT statement.

Here’s an example of how you can run a stored procedure using OPENROWSET:

SELECT *
FROM OPENROWSET('SQLNCLI',
'server=localhost;trusted_connection=yes;',
'EXEC [AdventureWorks].[dbo].[uspGetManagerEmployees] 5')

As you can see, it’s as simple as including the stored procedure call within the OPENROWSET function. This allows you to retrieve the results of the stored procedure directly in your SELECT statement.

If you encounter an error related to ad hoc queries when running the SELECT statement with OPENROWSET, you can fix it by executing the following commands:

sp_configure 'Show Advanced Options', 1
RECONFIGURE
sp_configure 'Ad Hoc Distributed Queries', 1
RECONFIGURE

These commands enable the use of ‘Ad Hoc Distributed Queries’ and resolve the error related to ad hoc queries.

And that’s it! You now know how to use stored procedures in SELECT statements using the OPENROWSET function. It’s a simple and efficient method to retrieve the results of a stored procedure within a SELECT statement.

If you found this topic interesting and would like me to create a video tutorial on it, please leave a comment below. I’m always open to suggestions and feedback from my readers.

Make sure to check out my recent videos on SQL in Sixty Seconds:

  • Performance Troubles – Function on Date Variable – SQL in Sixty Seconds #192
  • Performance: Between and Other Operators – SQL in Sixty Seconds #191
  • Most Used Database Files – SQL in Sixty Seconds #190
  • Optimize DATE in WHERE Clause – SQL in Sixty Seconds #189
  • Data Compression for Performance – SQL in Sixty Seconds #188
  • Get Current Time Zone – SQL in Sixty Seconds #187
  • Detecting Memory Pressure – SQL in Sixty Seconds #186
  • CPU Running 100% – SQL in Sixty Seconds #185
  • Generate Script of SQL Server Objects – SQL in Sixty Seconds #184
  • Prevent Unauthorized Index Modifications – SQL in Sixty Seconds #183
  • MAX Columns Ever Existed in Table – SQL in Sixty Seconds #182
  • Tuning Query Cost 100% – SQL in Sixty Seconds #181

If you have any questions or need further assistance, feel free to reach out to me on Twitter. I’m always here to help!

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.