sql - 如何重用存储过程中的结果以提供给同一存储过程中的第二个选择

标签 sql sql-server stored-procedures

我正在编写一个存储过程来获取整个屏幕的数据。我怎样才能重新使用一次选择的结果来输入第二次选择?这是出于性能原因

简化示例: 我有 4 张 table

  1. 负责
  2. Action(有 Responsible 的外键)
  3. 组(有 Responsible 的外键)
  4. 案例(有组的外键)

存储过程获取一个caseid来检索数据

首先select获取casegroup及其相关responsible记录的详细信息:

select 
   Case.Date,
   Case.Name,
   Group.Name,
   Responsible.Name
   Responsible.ResponsibleID
from Case
inner join Group on Group.GroupID=Case.GroupID
inner join Responsible on Responsible.ResponsibleID=Group.ResponsibleID
where CaseID=@CaseID

第二个选择必须得到负责人被分配到的所有 Action 。我们只有 caseID,因此我们必须再次重建连接:

select Action.*  
from Case
inner join Group on Group.GroupID=Case.GroupID
inner join Responsible on Responsible.ResponsibleID=Group.ResponsibleID
inner join Action  on Action.ResponsibleID=Responsible.ResponsibleID
where CaseID=@CaseID

如果可以重用先前结果中的变量,则可以创建以下查询,这可能会提高性能:

Select * from Action where ResponsibleID={ResultSet1}.ResponsibleID

最佳答案

考虑将结果保存在表变量中。这将允许您对永久表中的结果集执行多个 SQL 操作。

DECLARE @Case TABLE
(
    [CaseDate] datetime,
    [CaseName]  varchar(100),
    [GroupName] varchar(100),
    [ResponsibleName] varchar(100),
    [ResponsibleID] int
)

--get all your case details
INSERT INTO @Case( [CaseDate],[CaseName],
                   [GroupName],[ResponsibleName],[ResponsibleID])
SELECT 
   Case.Date,
   Case.Name,
   Group.Name,
   Responsible.Name
   Responsible.ResponsibleID
FROM      Case
INNER JOIN Group ON Group.GroupID=Case.GroupID
INNER JOIN Responsible ON Responsible.ResponsibleID=Group.ResponsibleID
WHERE CaseID=@CaseID


--now get the Action details for the previous case; 
--are we absolutely sure there is only one row? then an INNER JOIN 
SELECT A.*  
FROM   Action  AS [A] 
INNER JOIN @Case AS C ON A.ResponsibleID=C.ResponsibleID

-- or guard against multiple results in @Case
SELECT A.* FROM Action AS [A] 
WHERE A.ResponsibleID = (SELECT TOP 1 ResponsibleID FROM @Case) 

关于sql - 如何重用存储过程中的结果以提供给同一存储过程中的第二个选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5051781/

相关文章:

php - 知道哪一列有结果

c# - 更改 SqlConnection 超时

performance - 如何分析 Oracle 存储过程的端到端性能

sql-server - 如何为 SQL Server 数据库中的所有身份设置默认种子?

sql - 表拆分中的 T-SQL 日期范围并将单个日期添加到表中

c# - 从接收到的数据存储过程中填充自定义 C# 对象

mysql - MySQL正确调用存储过程

sql - 将 SQL Server 数据库移动到新服务器

c# - 关键字 'add' 附近的语法不正确

sql - 具有行版本控制的 PostgreSQL 数据库