3

I have a stored procedure which returns a Dataset(Table). How can I use the result of this stored procedure in a SELECT statement?

I need something like this

SELECT T1.* 
FROM Dummy T0
     INNER JOIN
     (EXEC [dbo].[SPGetResults] '900',300,'USD') T1 
     ON T1.aKey=T0.aKey

I'm using SQL Server 2005

shA.t
  • 15,880
  • 5
  • 49
  • 104
Salvador
  • 15,602
  • 32
  • 134
  • 238
  • 1
    select into a temp table: see http://stackoverflow.com/questions/653714/how-to-select-into-temp-table-from-stored-procedure – Mitch Wheat Oct 07 '10 at 05:29

5 Answers5

3

I agree with Marcelo mostly, but if you are set on using a stored procedure, or your stored procedure does anything that affects data, you could create a #temp table with the structure of the output of your stored procedure, and then do something like

INSERT INTO #temp
EXEC [dbo].[SPGetResults] '900',300,'USD'

And then do your joins and selects on the temp table.

shA.t
  • 15,880
  • 5
  • 49
  • 104
nathan gonzalez
  • 11,527
  • 4
  • 40
  • 57
1

Create a table-valued user-defined function instead.

Marcelo Cantos
  • 174,413
  • 38
  • 319
  • 360
1

The answer of Marcelo Cantos is the best one. Also for distributed queries you can use the following script:

USE [master]

sp_configure 'Ad Hoc Distributed Queries', 1
RECONFIGURE

USE [YourDB]

SELECT *
FROM OPENROWSET('SQLNCLI', 'Server=YourServer ;Trusted_Connection=yes;',
    'EXEC YourDB.YourSchema.YourSP ''YourParameters1'', YourParameters2') AS c
INNER JOIN YourTableOrView ap ON ap.YourPK = c.YourFK

http://www.kodyaz.com/articles/how-to-sql-select-from-stored-procedure-using-openquery-openrowset.aspx

shA.t
  • 15,880
  • 5
  • 49
  • 104
Mo Chavoshi
  • 545
  • 5
  • 15
0

Use Insert Into ... Exec and store the result into a Temp Table... Then you can join the Temp table in your select statement.

Alternatively as suggested before try converting the SP into a Table valued function.

This link provides much more options for you... http://www.sommarskog.se/share_data.html

The King
  • 4,572
  • 2
  • 35
  • 56
0

Here is a simple example of table Value user-defined function :

create function personSidsByLastName(@lastName varchar(20))
returns table
as 
return 
select personSid from Person where lastName like @lastName

select * from PersonAddress pa where pa.personSid in (select personSid from personSidsByLastName('ali'))
S'chn T'gai Spock
  • 1,027
  • 13
  • 16