Showing posts with label data files. Show all posts
Showing posts with label data files. Show all posts

Friday, 21 September 2012

Create Database Script

I always try to enforce standards across all the SQL Servers I manage, it makes tons of administrative tasks much easier to complete and ensures consistency across the estate.  One thing that really irritates me is existing “legacy” environments that do not conform to these standards.  For example I have server X which is running SQL Server 2005 on Windows Server 2003, this server was installed and configured long before I started working for my employer and has a disk configuration of;

C:\ - OS
D:\ - SQL Server files

With this non-standard drive configuration my standard create database script falls flat on its face as the Data and Log directories are hard coded (not brilliant I know but with consistency it works a treat :)  As my Standard installation guide specifies the Data and Log directory paths I know that any new servers will be consistent but the new script will also work for existing “legacy” servers with non-standard drive configurations.

Below is the modified script, It will create a database called dbLogging in the default data and log directories with a few other settings, which may or may not be what you require so get modding.  Yes it does assume that the database xabcx123xdbxdefaultxfilexpathx321xcbax does not exist, to be honest I don’t really care, if someone has a database with that name then I would love to know why.  If you do then you just need to do a find and replace to something more unconventional like say dbAdmin or dbSQLAdmin.

/*
      -----------------------------------------------------------------
      Create database with files in default the directories
      -----------------------------------------------------------------
   
      For more SQL resources, check out SQLServer365.blogspot.co.uk

      -----------------------------------------------------------------

      You may alter this code for your own purposes.
      You may republish altered code as long as you give due credit.
      You must obtain prior permission before blogging this code.

      THIS CODE AND INFORMATION ARE PROVIDED "AS IS"
    
      -----------------------------------------------------------------
*/
-- set database context
USE master;
GO

-- Create a temp database
CREATE DATABASE xabcx123xdbxdefaultxfilexpathx321xcbax;

-- Declare variables
DECLARE @DefaultDataFilePath VARCHAR(512)
DECLARE @DefaultLogFilePath VARCHAR(512)
DECLARE @DatabaseName VARCHAR(512)
DECLARE @DataFileName VARCHAR(517)
DECLARE @LogFileName VARCHAR(517)
DECLARE @DataFileExtension VARCHAR(4)
DECLARE @LogFileExtension VARCHAR(4)
DECLARE @SQL VARCHAR(4000)

/*
      *** THIS IS ALL YOU NEED TO SPECIFY ***
*/
SET @DatabaseName = 'dbLogging'

-- Set variables
SET @DataFileName = @DatabaseName + '_Data'
SET @LogFileName = @DatabaseName + '_Log'
SET @DataFileExtension = '.mdf'
SET @LogFileExtension = '.ldf'

-- Get the default data path  
SELECT @DefaultDataFilePath =   
(   SELECT LEFT(physical_name,LEN(physical_name)-CHARINDEX('\',REVERSE(physical_name))+1)
    FROM sys.master_files mf  
    INNER JOIN sys.databases d  
    ON mf.database_id = d.database_id  
    WHERE d.[name] = 'xabcx123xdbxdefaultxfilexpathx321xcbax' AND type = 0);

-- Get the default log path  
SELECT @DefaultLogFilePath =   
(   SELECT LEFT(physical_name,LEN(physical_name)-CHARINDEX('\',REVERSE(physical_name))+1)  
    FROM sys.master_files mf  
    INNER JOIN sys.databases d  
    ON mf.database_id = d.database_id
    WHERE d.[name] = 'xabcx123xdbxdefaultxfilexpathx321xcbax' AND type = 1);

-- Drop the temp database
IF EXISTS(SELECT 1 FROM master.sys.databases WHERE [name] = 'xabcx123xdbxdefaultxfilexpathx321xcbax' )  
BEGIN 
    DROP DATABASE xabcx123xdbxdefaultxfilexpathx321xcbax  
END;

-- If the database already exists print message tro client
IF EXISTS(SELECT 1 FROM master.sys.databases WHERE [name] = @DatabaseName) 
BEGIN
      -- Print message if database already exists
      PRINT 'Database ' + @DatabaseName + ' already exists on ' + @@SERVERNAME
END;

-- Build up SQL string to create database
IF NOT EXISTS(SELECT 1 FROM master.sys.databases WHERE [name] = @DatabaseName)  
BEGIN
      SET @SQL = 'CREATE DATABASE ' + '[' + @DatabaseName + ']' +'
      ON
      ( NAME = ' + '[' + @DataFileName + ']' + ',
            FILENAME = '''+ @DefaultDataFilePath + @DataFileName + @DataFileExtension + ''',
            SIZE = 1024MB,
            MAXSIZE = UNLIMITED,
            FILEGROWTH = 10% )
      LOG ON
      ( NAME = ' + '[' + @LogFileName + ']' + ',
            FILENAME = '''+ @DefaultLogFilePath + @LogFileName + @LogFileExtension + ''',
            SIZE = 1024MB,
            MAXSIZE = UNLIMITED,
            FILEGROWTH = 10% )'

-- Create the database
--Try Catch block to create database                 
      BEGIN TRY
            EXEC ( @SQL )
            PRINT @DatabaseName + ' has been created on ' + @@SERVERNAME
      END TRY
      BEGIN CATCH
            SELECT  @DatabaseName message_id,
                        severity,
                        [text],
                        @SQL
            FROM    sys.messages
            WHERE   message_id = @@ERROR
                        AND language_id = 1033 --British English
      END CATCH
END;
GO

Enjoy!

Chris

Wednesday, 1 February 2012

A Script A Day - Day 1 - Database File To Volume Mapping

Today is the 1st February 2012 and as promised here is the first of script in my "A Script A Day" series.  There will be 29 scripts (yes this year is a leap year:) which I will also roll-up into a single document and make available to you some time in March.


I have used the below script many times and used as a starting point for other more specific scenarios like getting information about new servers / databases, auditing and resource allocation.  The script maps database files to logical volumes and includes some additional file information for good measure.


/*
      ----------------------------------------------------------------- 
      Summary:                Server volume to database file mapping
      SQL Server Versions:    2005 onwards
      Written by:             Chris McGowan
      -----------------------------------------------------------------

      For more SQL resources, check out SQLServer365.blogspot.co.uk

      -----------------------------------------------------------------

      You may alter this code for your own purposes.
      You may republish altered code as long as you give due credit.
      You must obtain prior permission before blogging this code.
 
      THIS CODE AND INFORMATION ARE PROVIDED "AS IS"
     
      -----------------------------------------------------------------
*/
IF OBJECT_ID('tempdb..#DBFile') IS NULL
    CREATE TABLE #DBFile
        (
          [LogicalName] VARCHAR(200),
          [FileID] TINYINT,
          [FileName] VARCHAR(1000),
          [FileGroup] VARCHAR(100),
          [Size] VARCHAR(100),
          [MaxSize] VARCHAR(100),
          [Growth] VARCHAR(100),
          [Usage] VARCHAR(100)
        )
GO
IF OBJECT_ID('tempdb..#DBFile2') IS NULL
    CREATE TABLE #DBFile2
        (
          [VolumeLetter] CHAR(3),
          [LogicalFileName] VARCHAR(200),
          [FileID] TINYINT,
          [PhysicalFileName] VARCHAR(1000),
          [FileGroup] VARCHAR(100),
          [Size] VARCHAR(100),
          [MaxSize] VARCHAR(100),
          [Growth] VARCHAR(100),
          [Usage] VARCHAR(100)
        )
GO      
EXEC sp_Msforeachdb 'use [?];INSERT INTO #DBFile EXEC sp_helpfile'
GO
INSERT  INTO #DBFile2
        SELECT  LEFT([FileName], 3),
                [LogicalName],
                [FileID],
                [FileName],
                [FileGroup],
                [Size],
                [MaxSize],
                [Growth],
                [Usage]
        FROM    #DBFile
GO
SELECT  [VolumeLetter],
        [LogicalFileName],
        [PhysicalFileName],
        [FileID],
        [FileGroup],
        [Size],
        [MaxSize],
        [Growth],
        [Usage]
FROM    #DBFile2
ORDER BY [VolumeLetter] ASC
GO
IF OBJECT_ID('tempdb..#DBFile') IS NOT NULL
    DROP TABLE #DBFile
IF OBJECT_ID('tempdb..#DBFile2') IS NOT NULL
    DROP TABLE #DBFile2

Enjoy

Chris

Friday, 13 January 2012

Moving Database Files and Replication

Today’s post is a quick one as I am a bit under the cosh.

There are many ways to move database files, detach and attach, backup and restore, alter database.  But what can you do if the files you want to move belong to a database being used in replication?  Here is one solution I used recently;

USE master
GO
-- set database to restricted user mode
ALTER DATABASE databasename SET RESTRICTED_USER WITH ROLLBACK IMMEDIATE;
GO

-- set database offline
ALTER DATABASE databasename SET OFFLINE;
GO
-- modify database files
ALTER DATABASE databasename
MODIFY FILE ( NAME = logicalfilename, FILENAME = 'new file path' );
ALTER DATABASE databasename
MODIFY FILE ( NAME = logicalfilename, FILENAME = 'new file path' );
GO

-- move the files to the new drive / directory

-- set the database online
ALTER DATABASE databasename SET ONLINE;
GO

-- set the database to multi user
ALTER DATABASE databasename SET MULTI_USER;
GO

As always there are the usual precautions to take - never do this on a production system without testing it first!!!

Enjoy!

Chris