SQL SERVER – Using Stored Procedure in SELECT Statement

A very popular question I often receive during my Comprehensive Database Performance Health Check is about how to use stored procedures in SELECT Statement. Well, there are many methods to do that, let us learn the easiest way today.

SQL SERVER - Using Stored Procedure in SELECT Statement procselect-800x280

There are many different methods to get Stored Procedure’s results in the SELECT statement, such as creating a temp table, creating a table variable, using functions, and many more. However, here is the easiest method to run the stored procedure in SELECT statement.

For example here is the SP which you want to execute:

EXEC [AdventureWorks].[dbo].[uspGetManagerEmployees] 5
GO

You can run the following SELECT statement with the help of OPENROWSET and execute the stored procedure.

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

Yes, indeed it is that easy. When you run the SELECT statement with OPENROWSET and if you get an error about ad hoc queries, you can run the following command to fix the error.

Msg 15281, Level 16, State 1
SQL Server blocked access to STATEMENT ‘OpenRowset/OpenDatasource’ of component ‘Ad Hoc Distributed Queries’ because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of ‘Ad Hoc Distributed Queries’ by using sp_configure. For more information about enabling ‘Ad Hoc Distributed Queries’, search for ‘Ad Hoc Distributed Queries’ in SQL Server Books Online.

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

Well, that’s it for today. Isn’t it easy to learn about Using Stored Procedure in SELECT Statement? If you want me to create a video on this topic, just leave a comment, and I will be happy to do so.

Here are my few recent videos and I would like to know what is your feedback about them. Do not forget to subscribe SQL in Sixty Seconds series. I hope you appreciate learning about the last few SQL in Sixty Seconds Video.

If you have any questions, you can always reach out to me on Twitter.

Reference: Pinal Dave (https://darkslategrey-bat-805937.hostingersite.com)

Ad Hoc Query, SQL Server, SQL Stored Procedure
Previous Post
SQL SERVER – Most Used Database Files – Script
Next Post
SQL SERVER – Find Missing Identity Values

Related Posts

Leave a Reply