2011-12-06 38 views
0

我有一个大型库存系统,而且我不得不重新编写它的一部分I/O部分。它的核心是一张产品表格和一套相关的表格。我需要能够尽可能有效地阅读它的部分内容。从C#我建立这个查询:从多个连接表的子集中加载DataSet的最有效方法

select *         -- includes productid 
into #tt 
from products where productClass = 547  -- possibly more conditions 
select * from #tt; 
select * from productHistory where productid in (select productid from #tt); 
select * from productSuppliers where productid in (select productid from #tt); 
select * from productSafetyInfo where productid in (select productid from #tt); 
select * from productMiscInfo where productid in (select productid from #tt); 
drop table #tt; 

该查询给我完全的结果,我需要:5的结果集每个都具有零,一个或多个记录(如果第一个返回零行,别人做的一样好,的课程)。然后该程序将这些结果集合并将它们拼凑成合适的DataSet。 (然后将其交给构造函数,期望这些记录)。此查询(具有不同的条件)将运行lot

我的问题是,是否有更有效的方式来检索这些数据?

将此作为单个连接重新工作将不起作用,因为每个子可能会返回可变数量的行。

回答

1

如果您还没有它,我强烈建议将其作为一个存储过程。

此外,我怀疑,但不能证明没有测试它,如果您对每个子表的产品表执行联接而不是复制到本地表,您将获得更好的性能。

最后,除非您可以合并数据,否则我认为没有更有效的方法来执行此操作。

+0

一旦我找到了解决这个问题的最佳方法,我可能会将其解释为SP。至少在查询计划已经编译的地方。 –

2

如果您有products.productClass的索引,这可能会产生更好的性能。

select * from products where productClass = 547 -- includes productid  
    select productHistory.* 
    from productHistory 
    join products 
     on products.productid = productHistory.productid 
     and products,productClass = 547; 
    ... 

如果ProductID等于一个聚集索引,那么你将probalbly得到更好的permance与

CREATE TABLE #Temp (productid INT PRIMARY KEY CLUSTERED); 
    insert into #temp 
    select productid from products where productClass = 547 
    order by productid; 
    go 
    select productHistory.* 
    from productHistory 
    join #Temp 
     on #Temp.productid = productHistory.productid; 

一个连接上一个聚集索引,似乎提供最佳性能。 想一想 - SQL可以匹配第一个,并知道它可以忘记其余的然后移动到第二个知道它可以移动foward(不回到顶部)。
有一个where(select ..)SQL无法利用顺序。 你需要加入更多的表格#temp的更多原因,因为你需要花费大约1/2秒的时间创建填充#temp。 如果你打算去#temp,你可能会让它成为一个结构化的温度。

0

没有看到您的模式,并且知道更多关于您的数据和表大小的信息,很难在查询方面提出明确的改进建议。

然而,不是“填鸭式结果到合适的数据集,”因为你是使用批处理命令返回多个结果集,你可以使用的SqlDataAdapter做一部分,您:

SqlDataAdapter adapter = new SqlDataAdapter(cmd); 
DataSet results = new DataSet(); 
adapter.Fill(results); 

后第一个结果集将显示在results.Tables [0]中,第二个在results.Tables [1]中,等等。

2

确保何时您要加入索引的表为JOIN。否则,您将最终使用表扫描和索引扫描,并且您的代码在连接大型表时特别慢。

最佳做法是优化您的SQL查询以避免表扫描。

+0

您可以评论他在问题中发布的具体查询。 – ppaulojr

相关问题