Search This Blog

Code to list potential cluster key space savings per table

You can mess around with the code to do what you want. And I'm continuing to use sp_msforeachdb because it's the fastest way for me to knock out code for you, and it continues to irritate my good friend Aaron Bertrand :-)
Enjoy!
/*============================================================================
  File:     KeySpaceSavingsSingleResultSet.sql
  Summary:  Potential cluster key space savings
  SQL Server Versions: 2005 onwards
——————————————————————————
  Written by Paul S. Randal, SQLskills.com
  (c) 2012, SQLskills.com. All rights reserved.
  For more scripts and sample code, check out
    
http://www.SQLskills.com
  You may alter this code for your own *non-commercial* purposes. You may
  republish altered code as long as you include this copyright and give due
  credit, but you must obtain prior permission before blogging this code.

  THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF
  ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED
  TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
  PARTICULAR PURPOSE.
============================================================================*/
IF EXISTS (SELECT * FROM msdb.sys.objects WHERE [name] = 'SQLskillsIKSpace')
    DROP TABLE msdb.dbo.SQLskillsIKSpace;
GO
CREATE TABLE msdb.dbo.SQLskillsIKSpace (
    DatabaseID SMALLINT,
 SchemaName SYSNAME,
 ObjectName SYSNAME,
    ObjectID INT,
    IndexCount SMALLINT DEFAULT (0),
    TableRows BIGINT DEFAULT (0),
    KeyCount SMALLINT DEFAULT (0),
    KeyWidth SMALLINT DEFAULT (0));
GO
EXEC sp_MSforeachdb
    N'IF EXISTS (SELECT 1 FROM (SELECT DISTINCT [name]
    FROM sys.databases WHERE [state_desc] = ''ONLINE''
        AND [database_id] > 4
        AND [name] != ''pubs''
        AND [name] != ''Northwind''
        AND [name] != ''distribution''
        AND [name] NOT LIKE ''ReportServer%''
        AND [name] NOT LIKE ''Adventure%'') AS names WHERE [name] = ''?'')
BEGIN
USE [?]
INSERT INTO msdb.dbo.SQLskillsIKSpace
(DatabaseID, SchemaName, ObjectName, ObjectID)
SELECT DB_ID (''?''), SCHEMA_NAME (o.[schema_id]), OBJECT_NAME (o.[object_id]), o.[object_id]
FROM sys.objects o
WHERE o.[type_desc] IN (''USER_TABLE'', ''VIEW'')
    AND o.[is_ms_shipped] = 0
    AND EXISTS (
        SELECT *
        FROM sys.indexes
        WHERE [index_id] = 1
            AND [object_id] = o.[object_id]);
UPDATE msdb.dbo.SQLskillsIKSpace
SET [TableRows] = (
    SELECT SUM ([rows])
    FROM sys.partitions p
    WHERE p.[object_id] = [ObjectID]
    AND p.[index_id] = 1)
WHERE [DatabaseID] = DB_ID (''?'');

UPDATE msdb.dbo.SQLskillsIKSpace
SET [IndexCount] = (
    SELECT COUNT (*)
    FROM sys.indexes i
    WHERE i.[object_id] = [ObjectID]
    AND i.[is_hypothetical] = 0
    AND i.[is_disabled] = 0
    AND i.[index_id] != 1)
WHERE [DatabaseID] = DB_ID (''?'');
UPDATE msdb.dbo.SQLskillsIKSpace
SET [KeyCount] = (
    SELECT COUNT (*)
    FROM sys.index_columns ic
    WHERE ic.[object_id] = [ObjectID]
    AND ic.[index_id] = 1)
WHERE [DatabaseID] = DB_ID (''?'');
UPDATE msdb.dbo.SQLskillsIKSpace
SET [KeyWidth] = (
    SELECT SUM (c.[max_length])
    FROM sys.columns c
    JOIN sys.index_columns ic
    ON c.[object_id] = ic.[object_id]
    AND c.[object_id] = [ObjectID]
    AND ic.[column_id] = c.[column_id]
    AND ic.[index_id] = 1)
WHERE [DatabaseID] = DB_ID (''?'');
DELETE msdb.dbo.SQLskillsIKSpace
WHERE
    ([KeyCount] = 1 AND [KeyWidth] < 9)
    OR [IndexCount] = 0 OR [TableRows] = 0;
END';
GO
SELECT
 DB_NAME ([DatabaseID]) AS [Database],
 [SchemaName] AS [Schema],
 [ObjectName] AS [Table],
    [IndexCount] AS [NCIndexes],
    [KeyCount] AS [ClusterKeys],
    [KeyWidth],
    [TableRows],
    [IndexCount] * [TableRows] * [KeyWidth] AS [KeySpaceInBytes],
    ([IndexCount] * [TableRows] * ([KeyWidth] – 8)) AS [PotentialSavings]
FROM msdb.dbo.SQLskillsIKSpace
ORDER BY [PotentialSavings] DESC;
DROP TABLE msdb.dbo.SQLskillsIKSpace;
GO

Code to Generate the ALTER INDEX / DISABLE Command Statements 

  1. Disable all the table’s nonclustered indexes so that they aren’t automatically rebuilt when the clustered index is dropped in step 3. Because this is likely to be a one-time operation, use the query in Listing 1 (with the desired table name) to generate the ALTER INDEX statements.
  2. Listing 1: Code to Generate the ALTER INDEX Statements
    SELECT
            DISABLE_STATEMENT =
                    N'ALTER INDEX '
                    + QUOTENAME(si.[name], N']')
                    + N' ON '
                    + QUOTENAME(sch.[name], N']')
                    + N'.'
                    + QUOTENAME(OBJECT_NAME(so.[object_id]), N']')
                    + N' DISABLE'
            , ENABLE_STATEMENT =
                    N'ALTER INDEX '
                    + QUOTENAME(si.[name], N']')
                    + N' ON '
                    + QUOTENAME(sch.[name], N']')
                    + N'.'
                    + QUOTENAME(OBJECT_NAME(so.[object_id]), N']')
                    + N' REBUILD'
    FROM sys.indexes AS si
            JOIN sys.objects AS so
                    ON si.[object_id] = so.[object_id]
            JOIN sys.schemas AS sch
                    ON so.[schema_id] = sch.[schema_id]
    WHERE si.[object_id] = object_id('tablename')
            AND si.[index_id] > 1
    Note that you should use the column for DISABLE_STATEMENTS to disable the nonclustered indexes, and be sure to keep the enable information handy because you’ll need it to rebuild the nonclustered indexes after you’ve created the new clustered index.
  3. Disable any foreign key constraints. This is where you want to be careful if there are users using the database. In addition, this is also where you might want to use the following query to change the database to be restricted to only DBO use:
ALTER DATABASE DatabaseName
SET RESTRICTED_USER
WITH ROLLBACK AFTER 5
The ROLLBACK AFTER n clause at the end of the ALTER DATABASE statement lets you terminate user connections and put the database into a restricted state for modifications. As for automating the disabling of foreign key constraints, I leveraged some of the code from sp_fkeys and significantly altered it to generate the DISABLE command (similarly to how we did this in step 1 for disabling nonclustered indexes), which Listing 2 shows.
Listing 2: Code to Generate the DISABLE Command
SELECT
    DISABLE_STATEMENT =
                N'ALTER TABLE '
                + QUOTENAME(convert(sysname, schema_name(o2.schema_id)), N']')
                + N'.'
                + QUOTENAME(convert(sysname, o2.name), N']')
                + N' NOCHECK CONSTRAINT '
                + QUOTENAME(convert(sysname, object_name(f.object_id)), N']')
    , ENABLE_STATEMENT =
                N'ALTER TABLE '
                + QUOTENAME(convert(sysname, schema_name(o2.schema_id)), N']')
                + N'.'
                + QUOTENAME(convert(sysname, o2.name), N']')
                + N' WITH CHECK CHECK CONSTRAINT '
                + QUOTENAME(convert(sysname, object_name(f.object_id)), N']')
        , RECHECK_CONSTRAINT =
                N'SELECT OBJECTPROPERTY(OBJECT_ID('
                + QUOTENAME(convert(sysname, object_name(f.object_id)), N'''')
                + N'), ''CnstIsNotTrusted'')'
FROM
    sys.objects AS o1,
    sys.objects AS o2,
    sys.columns AS c1,
    sys.columns AS c2,
    sys.foreign_keys AS f
                INNER JOIN sys.foreign_key_columns AS k
                        ON (k.constraint_object_id = f.object_id)
                INNER JOIN sys.indexes AS i
                        ON (f.referenced_object_id = i.object_id
                                AND f.key_index_id = i.index_id)
WHERE
    o1.[object_id] = object_id('tablename')
        AND i.name = 'Primary key Name'
        AND o1.[object_id] = f.referenced_object_id
        AND o2.[object_id] = f.parent_object_id
        AND c1.[object_id] = f.referenced_object_id
        AND c2.[object_id] = f.parent_object_id
        AND c1.column_id = k.referenced_column_id
        AND c2.column_id = k.parent_column_id
ORDER BY 1, 2, 3
Use the column for DISABLE_STATEMENTS to disable the foreign key constraints, and keep the remaining information handy because you’ll need it to reenable and recheck the data, as well as verify the foreign key constraints after you’ve recreated the primary key as a unique nonclustered index.

Moving a database while Database Mirroring is running



I have a 600 gig database that has a mirror.  I need to move the databases from local drives to a SAN.  Can anyone recommend a document that lists the steps to go through to move both the principle and mirror to the SAN with no down time? or minimal down time?

As far as I know, there isn’t any such document so I had a crack at coming up with a list of operations. Here’s what I had:


  1. Take a full backup of the principal on node A
  2. Restore it on the SAN on node B using WITH NORECOVERY, remembering to use WITH MOVE to place the files correctly, and with a different database name than the current mirror
  3. Take the required log backup on the principal and restore on the database copy on the SAN on node B
  4. Break the mirroring partnership
  5. Drop the current mirror database on node B
  6. Rename the database on the SAN on node B to be the mirror database — THIS DOESN”T WORK!
  7. Setup the mirroring partnership to point to the newly restored database on the SAN on node B
  8. Start mirroring and the new mirror will catch-up
  9. Failover to the mirror on node B, which becomes the new principal
  10. Follow the same procedure to move the new mirror on node A onto its SAN
  11. Failback if you want to

And I promised to try it out to make sure I had it right so in this blog post I’m going to walk through the steps of doing this. It turns out that the steps above are slightly incorrect. Step 6 above doesn’t work because the database is in recovery (so is inaccessible) and there’s a short-cut when moving the database on the first node to avoid having to take and copy more backups. Let’s see how it works and I’ll post the corrected sequence at the end.

As I did in yesterday’s mirroring post, I’m going to use the TicketSalesDB database from our Always-On DVDs. It’s only a few hundred MB instead of 600GB but the principal is the same (no pun intended :-)). I’ve got mirroring running between two nodes, SQLDEV01 (the principal) and SQLDEV02 (the mirror), both of which are running 2005 SP2 and I’ve got a simulated workload inserting rows into the database. I don’t actually have a SAN laying around so I’m cheating and I have directories called C:\SQLDEV01SAN and C:\SQLDEV02SAN instead. It’s the location change that’s the interesting part, not where the actual location is.

Step 1

On SQLDEV01, take a full backup and a log backup:


BACKUP DATABASE TicketSalesDB TO DISK = ‘C:\SQLskills\TicketSalesDB.BAK’ WITH INIT;

GO


BACKUP LOG TicketSalesDB TO DISK = ‘C:\SQLskills\TicketSalesDB_Log.bak’ WITH INIT;

GO

Step 2

On SQLDEV01, break the mirroring partnership:


ALTER DATABASE TicketSalesDB SET PARTNER OFF;

GO

And just check that it’s gone:


SELECT mirroring_state_desc FROM sys.database_mirroring WHERE database_id = DB_ID (‘TicketSalesDB’);

GO

which returns:

NULL

Step 3

On SQLDEV02, drop the mirror database – this wouldn’t work unless mirroring was no longer running:


DROP DATABASE TicketSalesDB;

GO

Step 4

Copy the backups to SQLDEV02 and restore them on the SAN and remembering to use WITH NORECOVERY:


RESTORE DATABASE TicketSalesDB FROM DISK=‘C:\SQLskills\TicketSalesDB.bak’

WITH


MOVE ‘TicketSalesDBData’ TO ‘C:\SQLDEV02SAN\TicketSalesDBData.MDF’,

MOVE ‘TicketSalesFG2005Q1′ TO ‘C:\SQLDEV02SAN\TicketSalesFG2005Q1.NDF’,

MOVE ‘TicketSalesFG2005Q2′ TO ‘C:\SQLDEV02SAN\TicketSalesFG2005Q2.NDF’,

MOVE ‘TicketSalesFG2005Q3′ TO ‘C:\SQLDEV02SAN\TicketSalesFG2005Q3.NDF’,

MOVE ‘TicketSalesFG2005Q4′ TO ‘C:\SQLDEV02SAN\TicketSalesFG2005Q4.NDF’,

MOVE ‘TicketSalesDBLog’ TO ‘C:\SQLDEV02SAN\TicketSalesDBLog.LDF’,

NORECOVERY;

GO


RESTORE LOG TicketSalesDB FROM DISK = ‘C:\SQLskills\TicketSalesDB_Log.bak’ WITH NORECOVERY;

GO

Step 5

On SQLDEV02, set the mirroring partner to be SQLDEV01:


ALTER DATABASE TicketSalesDB SET PARTNER = ‘TCP://SQLDEV01:5091′;

GO

Step 6

On SQLDEV01, start mirroring:


ALTER DATABASE TicketSalesDB SET PARTNER = ‘TCP://SQLDEV02:5092′;

GO

And check that it’s running:


SELECT mirroring_state_desc FROM sys.database_mirroring WHERE database_id = DB_ID (‘TicketSalesDB’);

GO

This time it returns:

SYNCHRONIZED

Step 7

Now we need to failover so that we can move the database on SQLDEV01 onto its SAN. Before we do that, let’s make sure that SQLDEV01 is the principal:


SELECT mirroring_role_desc FROM sys.database_mirroring WHERE database_id = DB_ID (‘TicketSalesDB’);

GO

which returns:


PRINCIPAL

Now force the failover:

ALTER DATABASE TicketSalesDB SET PARTNER FAILOVER;

GO

And query the DMV again to make sure. This time the mirroring_state_desc returned is:


MIRROR


Excellent!

Now, I did all of this while my workload was running and it automatically failed over to SQLDEV02, with the database now hosted on the SAN. To do the same move on SQLDEV01, we don’t need to go through the backup and copy process again – we can just use the original backups we took in step 1.

Step 8

We need to break the mirroring partnership again, this time executing on SQLDEV02, the new principal:


ALTER DATABASE TicketSalesDB SET PARTNER OFF;

GO

On SQLDEV01, we can now drop the database and restore the original backups onto the SAN:


DROP DATABASE TicketSalesDB;

GO

RESTORE DATABASE TicketSalesDB FROM DISK=‘C:\SQLskills\TicketSalesDB.bak’

WITH


MOVE ‘TicketSalesDBData’ TO ‘C:\SQLDEV01SAN\TicketSalesDBData.MDF’,

MOVE ‘TicketSalesFG2005Q1′ TO ‘C:\SQLDEV01SAN\TicketSalesFG2005Q1.NDF’,

MOVE ‘TicketSalesFG2005Q2′ TO ‘C:\SQLDEV01SAN\TicketSalesFG2005Q2.NDF’,

MOVE ‘TicketSalesFG2005Q3′ TO ‘C:\SQLDEV01SAN\TicketSalesFG2005Q3.NDF’,

MOVE ‘TicketSalesFG2005Q4′ TO ‘C:\SQLDEV01SAN\TicketSalesFG2005Q4.NDF’,

MOVE ‘TicketSalesDBLog’ TO ‘C:\SQLDEV01SAN\TicketSalesDBLog.LDF’,

NORECOVERY;

GO

RESTORE LOG TicketSalesDB FROM DISK = ‘C:\SQLskills\TicketSalesDB_Log.bak’ WITH NORECOVERY;

GO

And setup mirroring again. On SQLDEV01:


ALTER DATABASE TicketSalesDB SET PARTNER = ‘TCP://SQLDEV02:5092′;

GO
And on SQLDEV02:


ALTER DATABASE TicketSalesDB SET PARTNER = ‘TCP://SQLDEV01:5091′;

GO
And we’re running again.

Step 9

Now all we need to do is fail the workload back to SQLDEV01 by executing this on SQLDEV02:


ALTER DATABASE TicketSalesDB SET PARTNER FAILOVER;

GO
Summary

So – the corrected sequence for moving a database while mirroring is running is the following:


  1. Take a full backup of the principal database on node A, and the required log backup
  2. Break the mirroring partnership
  3. Drop the current mirror database on node B 
  4. Copy the backups to node B and restore it on the SAN on node B using WITH NORECOVERY, remembering to use WITH MOVE to place the files correctly
  5. Setup the mirroring partnership to point to the newly restored database on the SAN on node B
  6. Start mirroring and the new mirror will catch-up
  7. Failover to the mirror on node B, which becomes the new principal
  8. Follow the same procedure to move the new mirror on node A onto its SAN, but using the original backups from step 1
  9. Failback