Remote Tech Support

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Friday, 20 August 2010

Shrink DB for SQL 2008

Posted on 02:09 by Unknown
Problem
There are times when a SQL Server transaction log file grows so large that it has to be shrunk back to a more reasonable size.  Before shrinking the log file it is necessary to remove the recent transaction log entries from the log.  That use to be done with the BACKUP LOG.... WITH TRUNCATE_ONLY command.  The TRUNCATE_ONLY option was removed in SQL Server 2008.  How do you remove the log entries so the transaction log file can be shrunk?

While Executing this query an stored procedure named as ns_shrink_db_log will be created in master database. It is one time work.

For Shrink database you should be execute the Stored Procedure only (ns_shrink_db_log)

EXEC dbo.ns_shrink_db_log
Here's the code: Copy and  Paste into the SQL Query Analyser
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROC [dbo].[ns_shrink_db_log]
   @db_name SYSNAME = NULL
  , @target_size_mb INT = 2
  , @backup_location NVARCHAR(200) = NULL
  , @backup_file_name NVARCHAR(200) = NULL
  , @maximum_attempts INT = 10
  
/* Shrinks the log file of @db_name to the @target_size_mb
*
exec [dbo].[ns_shrink_db_log] 'scratch', 2, 'c:\temp\'
             , 'scratch_shirnk_backup', 4
************************************************************/
AS
SET NOCOUNT ON
SELECT @db_name = COALESCE(@db_name, DB_NAME())
    
DECLARE @logical_log_file_name SYSNAME,
        @backup_log_sql NVARCHAR(MAX),
        @shrink_sql NVARCHAR(MAX),
        @checkpoint_sql NVARCHAR(MAX),
        @db_id INT = DB_ID (@db_name),
        @start_size_mb INT,
        @final_size_mb INT,
        @attempts INT = 0,
        @recovery_model INT,
        @recovery_model_desc SYSNAME,
        @rc INT = 0 -- return code
SELECT @logical_log_file_name = name,
       @start_size_mb = size / 128
   FROM MASTER..sysaltfiles
   WHERE dbid=@db_id AND  fileid=2
  
SELECT @recovery_model = recovery_model  
     , @recovery_model_desc = recovery_model_desc
   FROM sys.databases
   WHERE database_id=@db_id
  
PRINT 'Starting size of [' + @db_name + '].['
            + @logical_log_file_name
            + '] is '
            + CONVERT(VARCHAR(20), @start_size_mb) + ' MB '
            + ' recovery model = ' + @recovery_model_desc
IF @start_size_mb <= @target_size_mb BEGIN
   PRINT '['+@db_name+'] does not need shrinking'
    END
    
ELSE BEGIN    
          
    IF @recovery_model != 3
        AND (@backup_file_name IS NULL OR @backup_location IS NULL) BEGIN
        RAISERROR ('Null backup file location or name. aborting.', 16, 1)
        SET @rc = 50000
        GOTO get_out
    END
   WHILE @attempts < @maximum_attempts
      AND @target_size_mb < (SELECT CONVERT(INT, size/128) FROM MASTER..sysaltfiles
                               WHERE dbid = @db_id AND
                                      name = @logical_log_file_name) -- not target
      BEGIN
        SET @attempts = @attempts + 1
        
        IF @recovery_model= 3 BEGIN
           SET @checkpoint_sql = 'use ['+@db_name+']; '
                               + 'checkpoint'
           PRINT @checkpoint_sql
           EXEC (@checkpoint_sql)
            END
        ELSE BEGIN
           SET @backup_log_sql =  'BACKUP LOG ['+ @db_name + '] '
                              + ' to disk = ''' + @backup_location
                              + CASE WHEN RIGHT(RTRIM(@backup_location), 1)='\'
                                    THEN '' ELSE '\' END
                              + @backup_file_name
                              + CONVERT(VARCHAR(10), @attempts)
                             + '.trn'''
           PRINT @backup_log_sql              
           EXEC (@backup_log_sql) -- See if a trunc of the log shrinks it.
        END
              
       SET @shrink_sql = 'use ['+@db_name+'];'
                       + 'dbcc shrinkfile (['+@logical_log_file_name+'], '
                       + CONVERT(VARCHAR(20), @target_size_mb) + ')'
       EXEC (@shrink_sql)
    END
END
SELECT @final_size_mb = size/128
   FROM MASTER..sysaltfiles
   WHERE dbid = @db_id AND name = @logical_log_file_name
  
PRINT  'Final size of [' + @db_name + '].['
            + @logical_log_file_name
            + '] is ' +
       CONVERT(VARCHAR(20),@final_size_mb)
       + ' MB'
    
get_out:
RETURN @rc


EXEC [dbo].[ns_shrink_db_log] 'scratch', 2, 'c:\temp\', 'scratch_shrink_backup', 4
Email ThisBlogThis!Share to XShare to Facebook
Posted in SQL | No comments
Newer Post Older Post Home
View mobile version

0 comments:

Post a Comment

Subscribe to: Post Comments (Atom)

Popular Posts

  • Windows Server 2008 Core Command Guide
    Windows Server 2008 Core Command Guide What Command Set DNS IP Netsh int ipv4 set dns “local area connection” stat...
  • USB Disk Security 5.4.0.12
    USB Disk Security -  Download 100% protection against any threats via USB storage USB Disk Security is a top-rated antivirus utility that pr...
  • GDS COMMITTEE IMPLEMENTATION ORDERS RELEASED BY DIRECTORATE TODAY
    GDS COMMITTEE IMPLEMENTATION ORDERS RELEASED BY DIRECTORATE TODAY POSTAL DIRECTORATE ISSUED ORDERS TODAY FOR IMPLEMENTING THE GDS COMMITTEE ...
  • (no title)
    POSTAL RATES INDEX Letters / Book Post Registered Articl...
  • Most Useful Websites
           The list primarily highlights the lesser-known or undiscovered websites and misses out all-time favorites like Google Docs, Wikipedia...
  • Commands in Windows Vista
    Windows Vista Command Line List and Reference The list of commands available in the command line shell for Windows Vista is similar to that ...
  • Save queries in Windows Server 2003's Active Directory Users and Computers tool
    Windows Server 2003 administrators can’t live without the Active Directory Users and Computers tool. Here’s a quick look at the saved querie...
  • PDF into Word ( Document) converter
    PDF into Word ( Document) Converter         PDF2Word(pdf to word) software enable export the text, images and other contents from pdf docume...
  • THIRUKKURAL PDF DOWNLOAD (தமிழ் )
    CLICK HERE TO DOWNLOAD THIRUKKURAL (தமிழ்)    or CLICK HERE TO DOWNLOAD THIRUKKURAL (TAMIL & ENGLISH)    or CLICK HERE TO DOWNLOAD THIR...
  • How to shutdown computer automatically at a specific time
    Trick 1: Start > Run Type ' shutdown -s -t 1800 ' without quotes Click OK A dialog will appear showing the countdown t...

Categories

  • Computer Guidelines
  • Customer Care
  • DB Tools
  • Drivers
  • Entertainments
  • FAQ
  • For System Administrators
  • FTP
  • General Informations
  • General Knowledge
  • Guidelines
  • Hardwares
  • Health Tips
  • Internet Tips
  • Latest Software Updates
  • Network Trouble shooting
  • Printer Trouble shooting
  • Printing Tips
  • Recovery Tips
  • Registry Tips
  • Registry Tools
  • Security Guidelines
  • Security Tips
  • Software Tips
  • Softwares
  • SQL
  • Technology
  • Tips and Tricks
  • Tools
  • Trouble shooting
  • Useful Softwares
  • Utilities
  • Virus Solutions
  • Websites
  • windows 7
  • Windows Server
  • Windows Tips
  • Windows Vista
  • Windows XP FAQ

Blog Archive

  • ►  2011 (138)
    • ►  May (32)
    • ►  April (24)
    • ►  March (29)
    • ►  February (15)
    • ►  January (38)
  • ▼  2010 (241)
    • ►  December (55)
    • ►  November (40)
    • ►  October (21)
    • ►  September (35)
    • ▼  August (39)
      • RRR Candidates Appointment orders dtd 30/08/2010 (...
      • Windows Tips & Tricks
      • Health is Wealth
      • Windows Server Trouble shooting
      • Disable Password Requirements in Windows Server 20...
      • POSTAL DEPARTMENTAL COUNCIL JCM MEETING HELD TODAY...
      • Registry Problems
      • USB - Universal Serial Bus
      • Windows 7 or Vista won’t start, Computer shows bla...
      • What is Computer | Computer History
      • What Is A Computer Virus? An Introduction To Compu...
      • What to do when When Windows Crashes?
      • New Rupee Symbol Font
      • Alphabetical list of Web Building Glossary Terms.
      • RECRUITMENT OF POSTAL / SORTING ASSISTANTS( FOR TA...
      • Shrink DB for SQL 2008
      • Top 10 security enhancements in SQL Server 2005
      • How to Move Documents and Settings default locatio...
      • Why tablet PCs will be a hit
      • How to move SQL Server from one computer/server/ma...
      • SQL Server administration best practices
      • Command Prompt Commands Help
      • SQL Server 2005 Security Best Practices
      • SQL FAQ
      • Overview of SQL Server security model and security...
      • Speed Up Computer By 3 Times With Easy Windows Tweaks
      • SQL Server Security Model and Security Best Practices
      • How to hide drives from My Computer?
      • Start PC in Safe Mode to Diagnose a problem
      • Registry Tools
      • Microsoft Windows XP Registry Guide Book
      • LAN & Network Diagnostics
      • Installation of Windows XP - Step by Step
      • Computer Black Screen on Boot
      • 13 Ultimate Tips on How to Speed Up Computer for Free
      • SQL Simple Tutorial
      • SQL Server 2000 : installation, Backup & Restore
      • Windows XP - Error Codes
      • About Microsoft - Bill Gates
    • ►  July (23)
    • ►  June (5)
    • ►  May (2)
    • ►  April (12)
    • ►  March (4)
    • ►  February (2)
    • ►  January (3)
  • ►  2009 (26)
    • ►  December (5)
    • ►  November (3)
    • ►  October (4)
    • ►  September (5)
    • ►  August (3)
    • ►  July (5)
    • ►  June (1)
Powered by Blogger.

About Me

Unknown
View my complete profile