9

I have results that are generated by this stored procedure.

I want to join these results with data in another table. I've seen various examples of doing this be creating a temporary table and inserting into it, however, this would not be ideal as the stored procedure returns many dynamic columns which are subject to change. Is there a way to join them dynamically?

Example scenario:

Stored Procedure Returns This:

EXEC uspGetProductCategories

products_id | products_model | Leather Seats | Heated Seats | Tapedeck | Heater | Hybrid | Sunroof | Cruise Control
===================================================================================================================
100         | Saturn Vue     | N             | N            | Y        | N      | N      | N       | N
200         | Toyota Pruis   | Y             | N            | N        | Y      | Y      | N       | N
300         | Ford Focus     | N             | N            | N        | Y      | N      | N       | Y

I want to JOIN it with a SQL query that generates something like:

SELECT * FROM Products_Detail

products_id | manufacturer | purchaser | pay_type
=================================================
100         | GM           | GREG      | P
200         | TOYT         | SAM       | P
300         | FORD         | GREG      | L

In other words...

Is there a painless way to accomplish this? Here is some psedo code of what I'd like to achieve (though I'm aware that this doesn't work):

SELECT pd.*, sp.* FROM Products_Detail pd
    LEFT JOIN uspGetProductCategories sp ON pd.product_id = sp.product_id

Again, I know you can't do this, but hopefully it describes the logic I'm looking for.

Example Desired Output

products_id | manufacturer | purchaser | pay_type | products_model | Leather Seats | Heated Seats | Tapedeck | Heater | Hybrid | Sunroof | Cruise Control
=========================================================================================================================================================
100         | GM           | GREG      | P        | Saturn Vue     | N             | N            | Y        | N      | N      | N       | N
200         | TOYT         | SAM       | P        | Toyota Pruis   | Y             | N            | N        | Y      | Y      | N       | N
300         | FORD         | GREG      | L        | Ford Focus     | N             | N            | N        | Y      | N      | N       | Y
Community
  • 1
  • 1
hendridm
  • 105
  • 1
  • 1
  • 4
  • You must put result of SP into temp table or put JOIN into SP. – Hamlet Hakobyan Feb 25 '13 at 22:34
  • 1
    Ok, so there is no way to create a temp table (dynamically) without having to specify/hard code the column names? – hendridm Feb 25 '13 at 22:35
  • Does the code have to be in an SP? What about a UDF? If you must use the SP... would it be possible to just add this join into the stored procedure itself? – Michael Fredrickson Feb 25 '13 at 22:50
  • possible duplicate of [SQL Server - SELECT FROM stored procedure](http://stackoverflow.com/questions/1492411/sql-server-select-from-stored-procedure) – Andriy M Feb 25 '13 at 23:10
  • @MichaelFredrickson Some of us don't have control over the SP sources, yet have to add to (or even "correct") the results we get back from them so we can't just add our JOINs in. :-( – Brian Knoblauch Aug 30 '17 at 12:52

4 Answers4

3

If you cannot create a temp table with the data from the dynamic stored procedure, why not just join on the table directly:

DECLARE @cols AS NVARCHAR(MAX),
    @colsNull AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(categories_name) 
                    from Categories
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

select @colsNull = STUFF((SELECT ',IsNull(' + QUOTENAME(categories_name)+', ''N'')'+' as '+QUOTENAME(categories_name) 
                    from Categories
                    group by categories_name, categories_id
                    order by categories_id
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = '
            select *
            from Products_Detail pd
            left join
            (
              SELECT products_id,
                    products_model,' + @colsNull + ' from 
               (
                  select p.products_id,
                    p.products_model,
                    c.categories_name,
                    ''Y'' flag
                  from products p
                  left join Products_Categories pc
                    on p.products_id = pc.products_id
                  left join Categories c
                    on pc.categories_id = c.categories_id
              ) x
              pivot 
              (
                  max(flag)
                  for categories_name in (' + @cols + ')
              ) p 
            ) p 
              on pd.products_id = p.products_id'

execute(@query)

See SQL Fiddle with Demo

Taryn
  • 242,637
  • 56
  • 362
  • 405
0

Try using this ugly solution if no way to reorganize your code.

SELECT * INTO #tmp
FROM OPENROWSET('SQLNCLI', 'server=INSTANCENAME;database=DBNAME;trusted_connection=yes', 'uspGetProductCategories') A

You must have allowed Ad Hoc Distributed Queries in your server.

Hamlet Hakobyan
  • 32,965
  • 6
  • 52
  • 68
-1

You can do this:

        INSERT aTemptable 
        EXEC yourstoredproc

if #t has been defined but you cannot do select into #t and have it be created dynamically.

Tim
  • 8,669
  • 31
  • 105
  • 183
  • 1
    Wouldn't I have to define #aTemptable first with column names/types? – hendridm Feb 25 '13 at 22:38
  • Sorry, hit submit accidentally. – Tim Feb 25 '13 at 22:40
  • 1
    It seems to me that there would be a way to create the temp table where the columns are automatically defined based on the output of the SP. (Rather than having to hard-code/pre-define them manually) ? I mean, this was essentially done in the original SP. – hendridm Feb 25 '13 at 22:41
  • Read this: http://stackoverflow.com/questions/7368864/retrieve-column-definition-for-stored-procedure-result-set – Tim Feb 25 '13 at 22:46
-1
create proc sp_emp18
(
@cust_id int,@name varchar(20),@order_id int,@order_date date
)
as 
begin
select e.cust_id,e.name,d.order_id,d.order_date 
from 
customer e inner join orders d on e.cust_id=d.cust_id
end

exec sp_emp18 101,'ram',99,'2016-07-21'
Kusum
  • 501
  • 2
  • 11
  • 30
  • Although this code may help to solve the problem, providing additional context regarding _why_ and/or _how_ it answers the question would significantly improve its long-term value. Please [edit] your answer to add some explanation. – Toby Speight Aug 04 '16 at 21:12