Sql server 在SQL Server中,当第二个查询依赖于第一个查询输出时,如何在存储过程中写入两个查询
我想编写一个存储过程,其中有两个select查询,第二个查询有依赖于第一个查询输出的where子句,如下所示Sql server 在SQL Server中,当第二个查询依赖于第一个查询输出时,如何在存储过程中写入两个查询,sql-server,stored-procedures,Sql Server,Stored Procedures,我想编写一个存储过程,其中有两个select查询,第二个查询有依赖于第一个查询输出的where子句,如下所示 create procedure getRecord As Begin select * from tblUser where userName = 'Johan' select * from tblDistrict where id between @id1 and @id2 end 这里@id1和@id2是第一次查询的结果表
create procedure getRecord
As
Begin
select *
from tblUser
where userName = 'Johan'
select *
from tblDistrict
where id between @id1 and @id2
end
这里@id1
和@id2
是第一次查询的结果表的第一个和最后一个id试试这个
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
create procedure getRecord
As
Begin
select * from tblDistrict where id IN (select Id from tblUser Where userName = 'Johan')
End
试试这个
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
create procedure getRecord
As
Begin
select * from tblDistrict where id IN (select Id from tblUser Where userName = 'Johan')
End
使用子查询。 子查询是可以在其他查询中使用的查询。它们总是从最里面的查询开始执行。在您的案例中,只需使用第一个查询作为子查询,如下所示:
create procedure getRecord
AS
BEGIN
SELECT *
FROM tblDistrict
WHERE id IN (SELECT *
FROM tblUser
WHERE userName = 'Johan')
END
请记住,子查询很难读取和调试。您可能希望限制嵌套查询的数量并对其进行格式化,以便像这里的例子一样易于遵循。有多种方法可以实现这一点。 如果您只需要第二个查询的结果,而第一个查询只是为了过滤第二个查询的结果,那么您可以将第一个查询嵌套在联接中,例如
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之间使用是有原因的,因此没有更改逻辑来查找tblUser和tblDistrict之间“Johan”的确切id匹配
第二个示例可以很容易地修改为使用表变量而不是临时表。但是性能差异超出了这个问题的范围。您还需要过程之外的第一个查询的输出吗?是的,实际上我想用c代码调用这个过程,其中我有一个数据集,我想用这两个表填充数据集