How to write two queries in a stored procedure when second query depend on first query output in SQL Server

时间:2016-04-07 10:36:18

标签: sql-server stored-procedures

I want to write a stored procedure in which I have two select queries and second queries has where clause that depends on first query output, as

create procedure getRecord
As
Begin
    select * 
    from tblUser 
    where userName = 'Johan'

    select * 
    from tblDistrict 
    where id between @id1 and @id2
end

Here @id1 and @id2 are the first and last id of resultant table of first query

4 个答案:

答案 0 :(得分:1)

Try this

create procedure getRecord
As
Begin

 select * from tblDistrict where id IN (select Id from tblUser Where userName = 'Johan')

End

答案 1 :(得分:1)

有多种方法可以实现这一目标。 如果您只需要第二个查询的结果,而第一个只是过滤第二个查询的结果,那么您可以将第一个查询嵌套在连接中,例如。

select * 
from tblDistrict 
inner join (select 
           MAX(id) as maxId,
           MIN(id) as minId
        from tblUser  
        where userName = 'Johan') as tbl1 ON
   tblDistrict.id between tbl1.minId and tbl1.minId

如果需要来自两个查询的输出,则可以使用表变量或临时表。 e.g。

select * 
into #tmpTbl1
from tblUser 
where userName = 'Johan'

declare @minId INT,@maxId INT
select @minId=min(id),@maxId=max(id) from #tmpTbl1

select * from #tmpTbl1
select * from tblDistrict where id between @minId and @maxId

drop table #tmpTbl1

我假设你在minId和maxId之间使用是有原因的,因此没有改变逻辑来找到'&#​​39; Johan'在tblUser和tblDistrict之间

可以轻松修改第二个示例以使用Table变量而不是临时表。但是,性能差异超出了这个问题的范围。

答案 2 :(得分:0)

Try this

create procedure getRecord As Begin

declare @min_id int,
        @max_id int 

select @min_id = min(id),
       @max_id = max(id) 
  from tblUser 
  Where userName = 'Johan';


 select * from tblDistrict where id between @min_id and @max_id 

End

答案 3 :(得分:0)

使用子查询。

子查询是您可以在其他查​​询中使用的查询。它们总是从最里面的查询执行。根据您的情况,只需将第一个查询用作子查询,如下所示:

create procedure getRecord
AS
BEGIN

SELECT * 
FROM tblDistrict
WHERE id IN (SELECT * 
             FROM tblUser 
             WHERE userName = 'Johan')

END

请记住,子查询很难阅读和调试。您可能希望限制嵌套查询的数量并对其进行格式化,以便在此处很容易理解。