首先创建一个未开启行压缩功能的表,使用下面的SQL语句往表里插入一些数据:
- /****** Object: Table [dbo].[NoNCompressed Table]
- Script Date: 05/27/2009 02:24:23 ******/
- IF EXISTS (SELECT * FROM sys.objects
- WHERE object_id = OBJECT_ID(N'[dbo].[NoNCompressed Table]')
- AND type in (N'U'))
- DROP TABLE [dbo].[NoNCompressed Table]
- GO
- CREATE TABLE [NoNCompressed Table]
- (id int, FName varchar(100), LName varchar(100))
- --增加10,000行
- declare @n int
- set @n=0
- while @n<=10000
- begin
- insert into [NoNCompressed Table] values
- (1,'Adam','Smith'),(2,'Maria','carter'),(3,'Walter','zenegger')
- set @n=@n+1
- end
- GO
然后使用下面的SQL语句查询这个表占用的空间大小:
- EXEC sp_spaceused [NONCompressed Table]
返回结果:
- name,rows,reserved,data,index_size,unused
- NoNCompressed Table,30003 ,968 KB,944 KB,8 KB,16 KB
现在我们创建一个启用了行压缩的表,使用下面的SQL语句插入相同数量的数据:
- /****** Object: Table [dbo].[Compressed Table]
- Script Date: 05/27/2009 02:24:57 ******/
- IF EXISTS (SELECT * FROM sys.objects
- WHERE object_id = OBJECT_ID(N'[dbo].[Compressed Table]')
- AND type in (N'U'))
- DROP TABLE [dbo].[Compressed Table]
- GO
- CREATE TABLE [Compressed Table]
- (id int, FName varchar(100), LName varchar(100)) with
- (Data_compression = ROW)
- declare @n int
- set @n=0
- --添加10,000行
- while @n<=10000
- begin
- insert into [Compressed Table] values
- (1,'Adam','Smith'),(2,'Maria','carter'),(3,'Walter','zenegger')
- set @n=@n+1
- end
- GO
使用下面的SQL语句查询表的空间占用情况:
EXEC sp_spaceused [Compressed Table]
返回结果:
name,rows,reserved,data,index_size,unused
Compressed Table,30003 ,584 KB,576 KB,8 KB,0 KB
结果显示压缩表比非压缩表占用的空间小得多。
有一种情况是表中已经有很多数据,但现在需要进行压缩,该怎么办呢?在这种情况下,可以ALTER TABLE语句增加数据压缩功能,我们创建另一个未启用压缩功能的表来模拟一下,使用下面的SQL语句添加数据到表中:
- /****** Object: Table [dbo].[NoNCompressed Table] Script Date: 05/27/2009 02:24:23 ******/
- IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[NoNCompressed Table2]') AND type in (N'U'))
- DROP TABLE [dbo].[NoNCompressed Table2]
- GO
- CREATE TABLE [NoNCompressed Table2]
- (id int, FName varchar(100), LName varchar(100))
- declare @n int
- set @n=0
- while @n<=10000
- begin
- insert into [NoNCompressed Table2] values
- (1,'Adam','Smith'),(2,'Maria','carter'),(3,'Walter','zenegger')
- set @n=@n+1
- end
- GO
使用下面的SQL语句查询该表占用的空间大小:
- EXEC sp_spaceused [NONCompressed Table2]
返回结果:
- name,rows,reserved,data,index_size,unused
- NoNCompressed Table,30003 ,968 KB,944 KB,8 KB,16 KB
使用下面的ALTER TABLE语句启用表的压缩功能:
- ALTER TABLE [NoNCompressed Table2]
- REBUILD WITH (DATA_COMPRESSION = ROW );
然后使用下面的SQL语句查询表的空间占用情况:
- EXEC sp_spaceused [NONCompressed Table2]
返回结果:
name,rows,reserved,data,index_size,unused
NoNCompressed Table2,30003 ,592 KB,560 KB,8 KB,24 KB
【编辑推荐】