Wil*_*ley 9 sql-server sql-server-2012 except
比较两个大型结果/行集的最有效方法的当前建议似乎是使用EXCEPT
运算符。随着行大小的增加(更改@last 值),下面这个自包含的 SQL 脚本变得非常低效。我试图在组合表中找到唯一的条目,但没有任何改进。
DECLARE @first AS INT, @step AS INT, @last AS INT;
-- This script is comparing two record sets using EXCEPT
-- I want to find additions from OLD to NEW
-- As number of rows increase performance gets terrible
-- I don't have to use two tables. I could use one combined table but I want the same result as quickly as possible
-- Compare 100 to 110 rows - 0 seconds
-- Compare 1000 to 1010 rows - 1 seconds
-- Compare 10000 to 10010 rows - 16 seconds
-- Compare 100000 to 100010 rows - ABORT after 8 minutes (tables are populated in 18 seconds)
DECLARE @temptableOLD TABLE ([Result1] int);
SET @step = 1; SET @first = 1; SET @last = 100000
WHILE(@first <= @last) BEGIN INSERT INTO @temptableOLD VALUES(@first) SET @first += @step END
DECLARE @temptableNEW TABLE ([Result1] int);
SET @step = 1; SET @first = 1; SET @last = 100010
WHILE(@first <= @last) BEGIN INSERT INTO @temptableNEW VALUES(@first) SET @first += @step END
select * from @temptableNEW
except
select * from @temptableOLD
Run Code Online (Sandbox Code Playgroud)
EXCEPT
意味着一个DISTINCT
操作。
NOT EXISTS
如果这实际上不是必需的,我会使用。
但是,您遇到的问题很可能是由于与表变量相关的基数估计不佳,您在未索引的表上获得了嵌套循环。
select * from @temptableNEW
except
select * from @temptableOLD
OPTION (RECOMPILE)
Run Code Online (Sandbox Code Playgroud)
将能够考虑到每个表有 100K 行并给出不同的计划。
在 SQL Server 2012 中,您只能通过约束向表变量添加索引。如果值是唯一的,您可以使用
DECLARE @temptableOLD TABLE ([Result1] int UNIQUE CLUSTERED);
Run Code Online (Sandbox Code Playgroud)
添加索引。如果在两个表上都完成了计划(在添加重新编译提示之后)可能会使用合并连接。没有任何索引,我希望哈希连接。
归档时间: |
|
查看次数: |
1549 次 |
最近记录: |