SQL Server: why 'SPARSE' does not impact for a space?

188 views Asked by At

Why alter table <> alter column<> SPARSE does not have an effect in cases 1-3 but only in case 4? I.e. can we say that column can be declared as SPARSE only when creating?

I have tested this code in SQL2012.

-- 1
CREATE TABLE UnSparsed(ID INT IDENTITY(1,1),
FirstCol INT,
SecondCol VARCHAR(100),
ThirdCol SmallDateTime)
GO

INSERT INTO UnSparsed SELECT TOP 50000 NULL,NULL, NULL
FROM master..spt_values v1, 
     master..spt_values v2

GO
sp_spaceused 'UnSparsed'
GO
--- 2
alter table UnSparsed alter column FirstCol int SPARSE NULL
alter table UnSparsed alter column SecondCol VARCHAR(100) SPARSE NULL
alter table UnSparsed alter column ThirdCol SmallDateTime  SPARSE NULL
GO
sp_spaceused 'UnSparsed'
GO
--- 3
truncate table UnSparsed
GO
INSERT INTO UnSparsed SELECT TOP 50000 NULL,NULL, NULL
FROM master..spt_values v1, 
     master..spt_values v2

GO
sp_spaceused 'UnSparsed'
GO
DROP TABLE UnSparsed
GO
--- 4
CREATE TABLE UnSparsed(ID INT IDENTITY(1,1),
FirstCol INT SPARSE NULL,
SecondCol VARCHAR(100)  SPARSE NULL,
ThirdCol SmallDateTime  SPARSE NULL)
GO
INSERT INTO UnSparsed SELECT TOP 50000 NULL,NULL, NULL
FROM master..spt_values v1, 
     master..spt_values v2

GO
sp_spaceused 'UnSparsed'
GO

enter image description here

1

There are 1 answers

0
ZedZip On BEST ANSWER

It seems need to do

ALTER TABLE t REBUILD; 

after this action all is ok.