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.
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.
- 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, you can always reach out to me on Twitter.
Reference: Pinal Dave (http://blog.SQLAuthority.com)