Want to become a Vibe Coder? Join Vibe Coding Training here
x
C# Corner
Tech
News
Videos
Forums
Jobs
Books
Events
More
Interviews
Live
Learn
Training
Career
Members
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Refer
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
SQL Server Stored Procedure to Compress Tables
WhatsApp
Dharmesh Singh
Aug 10
2016
859
0
0
CREATE
PROCEDURE
dbo.usp_CompressNonPartitionedTables (
@compression_mode
VARCHAR
(10),
@
schema
VARCHAR
(30),
@size_thresholdKB
INT
)
AS
BEGIN
set
nocount
on
DECLARE
@tsql
VARCHAR
(200)
DECLARE
@tablename
VARCHAR
(60)
DECLARE
@expectedSavingKB
BIGINT
DECLARE
cur
CURSOR
FOR
(
SELECT
DISTINCT
t.
NAME
AS
table_name
FROM
sys.partitions p ,sys.tables t ,sys.schemas s
WHERE
p.object_id = t.object_id
AND
p.partition_number = 1
AND
t.schema_id = s.schema_id
AND
s.
NAME
= @
schema
AND
p.data_compression = 0);
-- Create results table
CREATE
TABLE
#estimated_savings (
[object_name] SYSNAME
,[schema_name] SYSNAME
,[index_id]
INT
,[partition_number]
INT
,[size_with_current_compression_settingKB]
BIGINT
,[size_with_requested_compression_settingKB]
BIGINT
,[sample_size_with_current_compression_settingKB]
BIGINT
,[sample_size_with_requested_compression_settingKB]
BIGINT
);
OPEN
cur
FETCH
NEXT
FROM
cur
INTO
@tablename
WHILE @@FETCH_STATUS = 0
BEGIN
INSERT
INTO
#estimated_savings
EXECUTE
sp_estimate_data_compression_savings @schema_name = @
schema
,@object_name = @tablename
,@index_id =
NULL
,@partition_number =
NULL
,@data_compression = @compression_mode;
SELECT
@expectedSavingKB = ([size_with_current_compression_settingKB] -
[size_with_requested_compression_settingKB])
FROM
#estimated_savings
IF (@expectedSavingKB > @size_thresholdKB)
BEGIN
SET
@tsql =
'ALTER TABLE '
+ @
schema
+
'.['
+ @tableName +
']'
+
' rebuild WITH( DATA_COMPRESSION = '
+ @compression_mode +
' )'
EXEC
(@tsql)
END
TRUNCATE
TABLE
#estimated_savings
FETCH
NEXT
FROM
cur
INTO
@tablename
END
CLOSE
cur
DEALLOCATE
cur
DROP
TABLE
#estimated_savings
set
nocount
off
END
GO
SQL Server Compress Tables
Compress Tables
Up Next
SQL Server Stored Procedure to Compress Tables