How to call or execute a Stored Procedure from inside a Select Statement

Posted on : 09-05-2012 | By : Devi Prasad | In : SQLServerPedia Syndication, Stored Procedures, T-SQL Code Examples

Share:

2


How to call or execute a Stored Procedure from Select Statement in SQL Server?

It is really simple to call a stored procedure from a select statement Using OPENROWSET.

Below TSQL Query calls the procedure sp_who from the select statement.

SELECT * FROM 
   OPENROWSET('SQLNCLI'
              ,'Server=(local);Trusted_Connection=Yes;Database=Master'
              ,'EXEC dbo.sp_Who')

Syntax:

SELECT * FROM 
   OPENROWSET('SQLNCLI'
              ,'Server=(local);Trusted_Connection=Yes;Database=Master'
              ,'EXEC [procedurename]')

Additional Information:
The data that is coming from the procedure can also be filtered in the where clause.

SELECT * FROM 
   OPENROWSET('SQLNCLI'
              ,'Server=(local);Trusted_Connection=Yes;Database=Master'
              ,'EXEC dbo.sp_Who')
where dbname = 'master'

The data from the execution of a select statement can be directly pushed into a table.

SELECT * INTO who2_table FROM 
   OPENROWSET('SQLNCLI'
              ,'Server=(local);Trusted_Connection=Yes;Database=Master'
              ,'EXEC dbo.sp_Who')
where dbname = 'master'

If the openrowset is disabled in the system, learn how to enable it using this link enable openrowset

Related to SQL Server 2005,SQL Server 2008,SQL Server 2012

(Visited 470 times, 1 visits today)



References : Devi Prasad (sqlserverlearner.com)

Need Help On SQL Server?

Cannot Find Solution to your problem (or) If you are looking for some help on SQL Server. Dont worry Click Here to Post your question and solve your issue.


Do you like my blog?

If you liked reading this blog, please help spread the word by sharing this blog with your friends.




Comments (2)

Appreciate your post.

This has some other good references regarding T-SQL EXEC statement:
http://msdn.microsoft.com/en-us/library/ms188332(SQL.105).aspx

SELECT * FROM OPENROWSET(‘SQLNCLI’
,’Server=(local);Trusted_Connection=Yes;Database=Master’
,’exec dbo.sp_getNewID A,13,@id)’)

Getting below error
Msg 15281, Level 16, State 1, Line 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.

Write a comment