I want to create an SQL script that creates a database. Right now, I have this:
CREATE DATABASE [Documents] ON PRIMARY
( NAME = N\'Documents\', FILENAME = N\'
Create the database 'Documents' and give file properties through an alter.
USE [master]
GO
CREATE DATABASE [Documents]
GO
ALTER DATABASE [Documents] MODIFY FILE
( NAME = N'Documents', SIZE = 512MB, MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )
GO
ALTER DATABASE [Documents] MODIFY FILE
( NAME = N'Documents_log', SIZE = 256MB, MAXSIZE = UNLIMITED, FILEGROWTH = 10% )
GO
This script is more portable and can be deployed in multiple servers without any modifications.
Take a Look on how to create a Default Path. See if it helps on what you are looking for.
Cheers,
You can create a database without specifying file details, like:
CREATE DATABASE Documents;
I believe that you can do
CREATE DATABASE [Documents]
without the ON .... and it will get created with defaults for path and the rest.
See How do I find the data directory for a SQL Server instance?
If you are using SQL Server 2012 or higher, you can find the default path using
select
InstanceDefaultDataPath = serverproperty('InstanceDefaultDataPath'),
InstanceDefaultLogPath = serverproperty('InstanceDefaultLogPath')
You can then use exec() to construct your CREATE DATABASE statement.
This is useful if you want the physical file names of your database to be different from the default name.
Adding onto @Blade's answer. Here's an example of getting the default path server properties and using the EXECUTE method:
DECLARE @DefaultDataPath varchar(max)
SET @DefaultDataPath = (SELECT CONVERT(varchar(max), SERVERPROPERTY('INSTANCEDEFAULTDATAPATH')))
DECLARE @DefaultLogPath varchar(max)
SET @DefaultLogPath = (SELECT CONVERT(varchar(max), SERVERPROPERTY('INSTANCEDEFAULTLOGPATH')))
EXECUTE('
CREATE DATABASE [blah] ON PRIMARY
( NAME = N''blah'', FILENAME = ''' + @DefaultDataPath + 'blah.mdf'', SIZE = 167872KB, MAXSIZE = UNLIMITED, FILEGROWTH = 16384KB )
LOG ON
( NAME = N''blah_Log'', FILENAME = ''' + @DefaultDataPath + 'blah_Log.mdf'', SIZE = 2048KB, MAXSIZE = 2048GB, FILEGROWTH = 16384KB );
COLLATE SQL_Latin1_General_CP1_CI_AS;
');
GO
Note that if you do a USE
to switch dbs, the local variable scope is lost. So if you're creating multiple dbs in a script, either create them all at the beginning or copy the variables' declare/set to each create.