易截截图软件、单文件、免安装、纯绿色、仅160KB

SQL Server中的联合主键、聚集索引、非聚集索引

我们都知道在一个表中当需要2列以上才能确定记录的唯一性的时候,就需要用到联合主键,当建立联合主键以后,在查询数据的时候性能就会有很大的提升,不过并不是对联合主键的任何列单独查询的时候性能都会提升,但我们依然可以通过对联合主键中的首列除外的其他列建立非聚集索引来提高性能。
本文将对联合主键、聚集索引、非聚集索引对查询性能的影响举例说明。
步骤一,建立一个测试表,并且插入350万条以上的数据。
 
/*创建测试数据表*/
create table MyTestTable
(
id varchar(10)not null,
parent varchar(40) not null,
addtime datetime default(getdate()),
intcolumn int default(10),
bitcolumn bit default(1)
)
go
/*添加万条随机字符串测试数据耗时分钟*/
declare @count int=3557643
declare @i int =0
declare @id varchar(10),@parent varchar(40)
while(@i<@count)
begin
select @id=left(newid(),10)
if(@i % 20=0)
begin
select @parent=left(newid(),40)
end
insert MyTestTable(id,parent) values(@id,@parent)
select @i=@i+1
end
go
 
步骤二,不建立任何索引查询测试
/*未建立索引时的查询*/
declare @beginTime datetime =getdate()
declare @elapsedSecond int =0
select * from MyTestTable where parent='DD7D9F34-3A9C-43CA-836B-F2BABD78CE70' and id='103ACE5C-7'
select @elapsedSecond=DATEDIFF(MICROSECOND,@beginTime,GETDATE())
print '未建立索引时查找数据消耗微秒数'
print @elapsedSecond
select @beginTime=GETDATE()
select * from MyTestTable where parent='F535C18F-BD48-4D45-88DF-9653BB9B422D'
select @elapsedSecond=DATEDIFF(MICROSECOND,@beginTime,GETDATE())
print '未建立索引时查找第二列数据消耗微秒数'
print @elapsedSecond
--(1 row(s) affected)
--未建立索引时查找数据消耗微秒数
--530000
--(20 row(s) affected)
--未建立索引时查找第二列数据消耗微秒数
--500000
从执行结果我们可以看出,当没有索引的时候,SQL Server会遍历整个表,因此需要很长的时间。
步骤三,建立联合主键(会自动创建聚集索引)并查询测试
go
/*建立联合主键*/
alter table MyTestTable add constraint PK_id_parent primary key(id asc,parent asc)
/*建立索引后的查询*/
declare @beginTime datetime =getdate()
declare @elapsedSec


相关文档:

Interbase/Firebird的SQL语法(收藏)


一、分页写法小例:
SELECT FIRST 10 templateid,code,name from template ;
SELECT FIRST 10 SKIP 10 templateid,code,name from template ;
SELECT * from shop ROWS 1 TO 10;   –firebird2.0支持这种写法
 
二、显示表名和表结构
SHOW TABLES;
SHOW TABLE tablename;
四、更新字段注释
......

SQL Server 数据格式修改时,没有保存按钮的情况解决

如果你使用的是 SQL Server 2008, 当你修改数据结构后,保存时会报下图情况: Saving changes is not permitted. The changes you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving cha ......

用SQL语句拼接数据库表中一列的数据

最近在一个项目中遇到需要在数据层就拼接表中一列数据的问题。
例如,test表中有个字段t,t列中的4行数据为1,2,3,4 ,要拼接成1+2+3+4,琢磨了一阵,本来想用游标,但是效率。。后来找到一段SQL,可以很方便地拼接。
DECLARE @STR VARCHAR(8000) ----定义查询字符串
SELECT @STR=ISNULL(@STR+'+','')+t from (SELECT DIST ......

SQL Server、Oracle和MySQL中查出值为NULL的替换

SOURCE: CLICK HERE
本文讲述SQL Server、Oracle、MySQL查出值为NULL的替换。
在SQL Server Oracle MySQL当数据库中查出某值为NULL怎么办?
1、MSSQL: ISNULL()
语法
ISNULL ( check_expression , replacement_value )
参数
check_expression
将被检查是否为 NULL的表达式。check_expression 可以是任何类型的。
re ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号