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
  • 16,580
  • 5
  • 54
  • 111
Salvador
  • 16,132
  • 33
  • 143
  • 245
  • 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
  • 16,580
  • 5
  • 54
  • 111
nathan gonzalez
  • 11,817
  • 4
  • 41
  • 57
1

Create a table-valued user-defined function instead.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
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
  • 16,580
  • 5
  • 54
  • 111
Mo Chavoshi
  • 565
  • 5
  • 16
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,600
  • 3
  • 39
  • 58
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,203
  • 18
  • 16