SQL SERVER compression statement

Source: Internet
Author: User

The statement for compressing a database is as follows:

 

CREATE Procedure [dbo]. [sp_Compress]
AS

BEGIN
DECLARE @ db_name varchar (200)
Set @ db_name = 'dangjiae '-- Database Name
Dump transaction @ db_name WITH NO_LOG
Backup log @ db_name WITH NO_LOG
Dbcc shrinkdatabase (@ db_name)

END

 

 

 

SQL server 2005 compresses all database and log file statements in an instance

 

-- 01.get all database name
Select dbname = DB_NAME (s_mf.database_id) INTO # DN
FROM
Sys. master_files s_mf
WHERE
S_mf.state = 0 and -- ONLINE
HAS_DBACCESS (DB_NAME (s_mf.database_id) = 1 -- Only look at databases to which we have access
Group by s_mf.database_id
Order by 1
-- 02.use cursor to fetch db name
----- 02.01 declare cursor
DECLARE cur CURSOR
Select dbname from # DN

----- 02.02 open cursor & declare var
OPEN cur
DECLARE @ DbName VARCHAR (200)
----- 02.03 loop db bane
Fetch next from cur into @ DbName
WHILE (@ FETCH_STATUS = 0)
BEGIN
Print 'shrinking' + @ DbName + '...'
--------- 02.04 only shink log file

Exec (
'
Declare @ dn varchar (200 );
Declare @ ln varchar (210 );
Select @ dn = name from '+ @ DbName +'. dbo. sysfiles where fileid = 1
Select @ ln = name from '+ @ DbName +'. dbo. sysfiles where fileid = 2
Use ['+ @ DbName +'] backup log ['+ @ DbName +'] with no_log dbcc shrinkfile (@ ln)
'
)

------- 02.04 shink db file & log file
-- Dbcc SHRINKDATABASE (@ DbName)
Print @ DbName + 'done'
Fetch next from cur INTO @ DbName
END
----- 02.05 colse cursor
CLOSE cur
DEALLOCATE cur
----- 03. drop temp table
Drop table # DN
-------------------------------
The SQL and logs on the test server are often too large. Write a stored procedure and run the job periodically to avoid disk space waste.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.