从存储过程中查询存储过程

时间:2011-08-18 06:48:00

标签: sql sql-server stored-procedures

好吧,这可能是我的另一个不好的问题,但我仍然充满希望。如果你查看我最近的question,那是一种绝望的尝试,以简化将存储过程嵌套在另一个内部的需要。

基本上,我需要从视图(view_game)中选择满足特定条件的几行,并生成其他视图(view_pupil_game,view_pupil_doubles,view_game_winner)并组合输出以创建另一个视图。

但是,展望替代方案我想创建一个存储过程,它接受一个参数并将其提供给其他过程,并将输出作为结果集并使用它来完成主过程。

请帮助我,给出一个将存储过程视为表(或记录集)并在存储过程中查询它的简单示例

更新

要想知道我想要什么,这是一个虚拟查询

begin
Create procedure someProcedure
    @param1 int(3),
    @param2 int(3) 
as
begin
    SELECT * FROM <anotherStoreProcedure @param1, @param2> as set1 
    inner join <anotherStoreProcedure2 @param1, @param2> as set2 on set2.id=set1.id
end
go

2 个答案:

答案 0 :(得分:2)

可能你需要这样的东西:

-- tables to save result of calling stored procs below
DECLARE @set1 AS TABLE(id INT, value1 varchar(10))
DECLARE @set2 AS TABLE(id INT, value2 varchar(10))

-- save result of dbo.anotherStoreProcedure call into table variable @set1
INSERT INTO @set1 (id, value1)
EXEC dbo.anotherStoreProcedure @param1, @param2

-- save result of dbo.anotherStoreProcedure2 call into table variable @set2
INSERT INTO @set2 (id, value12)
EXEC dbo.anotherStoreProcedure2 @param1, @param2

SELECT 
  * 
FROM 
  set1 
INNER JOIN 
  set2 
ON 
  set2.id = set1.id

答案 1 :(得分:0)

您可以创建返回某些数据的表值UDF,然后您可以在SP中使用这些UDF。

示例:

create function SomeFunction1
(
  @param1 int,
  @param2 int
) returns table as 
return
(
  -- Some query that returns something
  select 1 as id,
         @param1 as Col1,
         'SomeFunc1' as Col2
  union all
  select 2, 
         @param2,
         'SomeFunc1' as Col2
)

go

create function SomeFunction2
(
  @param1 int,
  @param2 int
) returns table as 
return
(
  -- Some query that returns something else
  select 1 as id,
         @param1 as Col1,
         'SomeFunc2' as Col2
  union all
  select 2, 
         @param2,
         'SomeFunc2' as Col2
)

go

create procedure SomeProcedure
    @param1 int,
    @param2 int 
as
begin
  -- SP that uses the UDF and joins on column id
  select * 
  from dbo.SomeFunction1(@param1, @param2) as set1 
    inner join SomeFunction2(@param1, @param2) as set2 
      on set2.id=set1.id
end

像这样使用:

exec SomeProcedure 3, 4

结果:

id          Col1        Col2      id          Col1        Col2
----------- ----------- --------- ----------- ----------- ---------
1           3           SomeFunc1 1           3           SomeFunc2
2           4           SomeFunc1 2           4           SomeFunc2