SQL Server 2008:将 STORED PROCEDURE(动态列)的结果与 SELECT 语句的结果连接起来

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15077755/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 13:54:41  来源:igfitidea点击:

SQL Server 2008: Joining results of STORED PROCEDURE (dynamic columns) with results of a SELECT statement

sqlsql-serverstored-proceduresjoin

提问by hendridm

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 tableand inserting into it, however, this would not be ideal as the stored procedure returns many dynamic columnswhich 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:

我想用一个生成如下内容的 SQL 查询来加入它:

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):

有没有一种无痛的方法来实现这一点?这是我想要实现的一些 psedo 代码(尽管我知道这不起作用):

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

采纳答案by Taryn

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

参见SQL Fiddle with Demo

回答by Hamlet Hakobyan

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 Queriesin your server.

您必须Ad Hoc Distributed Queries在您的服务器中允许。

回答by saikrishna

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'

回答by Tim

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.

如果#t 已定义,但您不能选择#t 并动态创建它。