Did you sort it out, Andy?
In the past I have created new databases from scratch using the SQL Server Command Line Tool sqlcmd.exe and database scripts for the schema, initialisation of data etc.
I used a Windows Command Script called CreateDatabase.cmd which accepted the database instance name and database name as parameters and then fired off the sql scripts. Using a cmd file means you can get it working outside of NSIS first, and you can recreate databases outside of your installer at any time.
CreateDatabase.cmd
@echo off
setlocal
rem cls
IF "%~1"=="" (
SET a=2
SET ErrorText=No database instance name provided.
Goto Error
) ELSE (SET Instance=%~1)
IF "%~2"=="" (
SET a=3
SET ErrorText=No database name provided.
Goto Error
) ELSE (SET Database=%~2)
Title Creating database "%Database%" on "%Instance%"
echo Creating database...
sqlcmd -S "%Instance%" -b -v Database="%Database%" SQLPath="" -i CreateDatabase.sql
SET a=%ErrorLevel%
IF %a%==0 (
echo ...Successfully created database.
) ELSE (
rem SET a=1
SET ErrorText=Failed to create database.
Goto Error
)
echo Creating database schema...
sqlcmd -S "%Instance%" -b -d "%Database%" -i DatabaseSchema.sql
IF %ErrorLevel%==0 (
echo ...Successfully created database schema.
) ELSE (
SET a=2
SET ErrorText=Failed to create database schema.
Goto Error
)
echo Running initialisation scripts...
sqlcmd -S "%Instance%" -b -d "%Database%" -i Initialisation.sql
IF %ErrorLevel%==0 (
echo ...Successfully ran initialisation scripts.
) ELSE (
SET a=3
SET ErrorText=Failed to run initialisation scripts.
Goto Error
)
...
CreateDatabase.sql
:On Error exit
--:Out null
--:SetVar SQLCMDERRORLEVEL 18
DECLARE @Database varchar(64);
DECLARE @Error int;
DECLARE @Path varchar(256);
SET @Database = '$(Database)';
SET @Path = '$(SQLPath)';
IF @Path IS NULL OR RTrim(@Path) = ''
SET @Path = (SELECT SUBSTRING(physical_name, 1, CHARINDEX('master.mdf', LOWER(physical_name)) - 1)
FROM master.sys.master_files
WHERE database_id = 1 AND file_id = 1);
ELSE IF Right(@Path, 1) != '\'
SET @Path = @Path + '\';
IF EXISTS(SELECT [name] as [Database]
FROM master.sys.databases
WHERE [name] = @Database)
RAISERROR ('Database already exists.', 18, 10); -- :Exit(SELECT 10)
IF EXISTS(SELECT [name]
FROM master.sys.master_files
WHERE physical_name = @Path + @Database + '.mdf' OR physical_name = @Path + @Database + '_log.ldf')
RAISERROR ('Database files already exist.', 18, 11); -- :Exit(SELECT 11)
EXECUTE('CREATE DATABASE ' + @Database + ' ON PRIMARY
(NAME = ' + @Database + ', FILENAME = ''' + @Path + @Database + '.mdf'', FILEGROWTH = 1024KB)
LOG ON
(NAME = ' + @Database + '_log, FILENAME = ''' + @Path + @Database + '_log.ldf'', FILEGROWTH = 10%)
COLLATE SQL_Latin1_General_CP1_CI_AI');
IF @@Error != 0
RAISERROR ('Failed to creating database.', 18, 12); -- :Exit(SELECT 2)
And then exec the cmd file with:
nsExec::ExecToLog '"$TEMP\CreateDatabase.cmd" $SQL_INSTANCE $DB_NAME'