Assuming you are using SQL Server 2005 or 2008 this should do it. Although it's probably a bit longer than you expected :-) You could put the main part of the code into a function and call that every time you need to create a database.
declare @instance_name nvarchar(200),
@system_instance_name nvarchar(200),
@registry_key nvarchar(512),
@path_data nvarchar(260),
@path_log nvarchar(260),
@value_name nvarchar(20),
@script nvarchar(4000);
set @instance_name = coalesce(convert(nvarchar(20), serverproperty('InstanceName')), 'MSSQLSERVER');
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\Microsoft SQL Server\Instance Names\SQL', @instance_name, @system_instance_name output;
set @registry_key = N'Software\Microsoft\Microsoft SQL Server\' + @system_instance_name + '\MSSQLServer';
/* determine default location for data files */
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', @registry_key, N'DefaultData', @path_data output;
if @path_data is null
begin
/* this is only executed if we are using the default instance */
set @registry_key = N'Software\Microsoft\Microsoft SQL Server\' + @system_instance_name + '\Setup';
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', @registry_key, N'SQLDataRoot', @path_data output;
set @path_data = @path_data + '\Data';
end;
/* determine default location for log files */
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', @registry_key, N'DefaultLog', @path_log output;
if @path_log is null
begin
/* this is only executed if we are using the default instance */
set @registry_key = N'Software\Microsoft\Microsoft SQL Server\' + @system_instance_name + '\Setup';
exec master.dbo.xp_regread N'HKEY_LOCAL_MACHINE', @registry_key, N'SQLDataRoot', @path_log output;
set @path_log = @path_log + '\Data';
end;
set @script = 'CREATE DATABASE [asst]
ON (NAME = ''asst_dat'', FILENAME = ''' + @path_data + '\yourfile.mdf'' , SIZE = 62, FILEGROWTH = 10%)
LOG ON (NAME = ''asst_log'', FILENAME = ''' + @path_log + '\yourfile.ldf'' , SIZE = 146, FILEGROWTH = 10%);'
exec(@script);
You can not use variables in the CREATE DABASE
statement. That's why you have to create a variable that holds the command and execute that as a script.