sql server程序优化
SQl Server 2005:
Option: 1
CREATE TABLE #test
(customerid, orderdate, field1 INT, field2 INT, field3 INT)
CREATE UNIQUE CLUSTERED INDEX Idx1 ON #test(customerid)
CREATE INDEX Idx2 ON #test(field1 DESC)
CREATE INDEX Idx3 ON #test(field2 DESC)
CREATE INDEX Idx4 ON #test(field3 DESC)
INSERT INTO #test
(customerid, orderdate, field1 INT, field2 INT, field3 INT)
SELECT
customerid, orderdate, field1, field2, field3 FROM
ATABLERETURNING4000000ROWS
相比
Option: 2
CREATE TABLE #test
(customerid, orderdate, field1 INT, field2 INT, field3 INT)
INSERT INTO #test
(customerid, orderdate, field1 INT, field2 INT, field3 INT)
SELECT
customerid, orderdate, field1, field2, field3 FROM
ATABLERETURNING4000000ROWS
CREATE UNIQUE CLUSTERED INDEX Idx1 ON #test(customerid)
CREATE INDEX Idx2 ON #test(field1 DESC)
CREATE INDEX Idx3 ON #test(field2 DESC)
CREATE INDEX Idx4 ON #test(field3 DESC)
当我们使用第二个选项时,它的运行速度快了近 50%。这是为什么呢?
SQl Server 2005:
Option: 1
CREATE TABLE #test
(customerid, orderdate, field1 INT, field2 INT, field3 INT)
CREATE UNIQUE CLUSTERED INDEX Idx1 ON #test(customerid)
CREATE INDEX Idx2 ON #test(field1 DESC)
CREATE INDEX Idx3 ON #test(field2 DESC)
CREATE INDEX Idx4 ON #test(field3 DESC)
INSERT INTO #test
(customerid, orderdate, field1 INT, field2 INT, field3 INT)
SELECT
customerid, orderdate, field1, field2, field3 FROM
ATABLERETURNING4000000ROWS
compared to
Option: 2
CREATE TABLE #test
(customerid, orderdate, field1 INT, field2 INT, field3 INT)
INSERT INTO #test
(customerid, orderdate, field1 INT, field2 INT, field3 INT)
SELECT
customerid, orderdate, field1, field2, field3 FROM
ATABLERETURNING4000000ROWS
CREATE UNIQUE CLUSTERED INDEX Idx1 ON #test(customerid)
CREATE INDEX Idx2 ON #test(field1 DESC)
CREATE INDEX Idx3 ON #test(field2 DESC)
CREATE INDEX Idx4 ON #test(field3 DESC)
When we use the second option it runs close to 50% faster. Why is this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自 SQL Server 查询处理团队:
您的索引是 B+ 树。
第一个查询需要在 B+ 树中查找每条记录,并且然后修改B+树。
第二个查询将根据特定索引依次对每个索引所需的数据进行排序,B+树为 构建非常高效。
From the SQL Server Query Processing Team:
Your indexes are B+ trees.
The first query requires lookups in B+ trees for each record and then modifying the B+ trees.
The second query will sort the data reuired for each index in turn according to the particular index and the B+ trees are constructed very efficiently.
因为您是在添加索引之前插入行。唯一索引要求系统对新添加的行执行唯一性检查,并且在插入时,系统必须更新各个索引条目。不必执行唯一性检查工作会更快,但如果存在重复的 customerId 值,则在第二个选项中索引创建将失败。
Because you are inserting the rows before you add the indexes. The unique index requires that the system perform uniqueness checks on the newly added rows and on insert, the system must update the various index entries. Not having to do the work of uniqueness checks is faster but your index creation will fail in the second option if there are duplicate customerId values.