I've been struggling with this for several days. I have an application that uses a SQL SERVER database for storing its data. This database has several tables, stored procedures, functions and views.
I used to generate a large database creation script for deployments. Now, I'd like to have one script/file per object, and a main script to run all those scripts.
Using sqlcmd mode, I've made a script that lists all files in a path, and creates another file with the execution of all files from that path.
--DECLARE PATH
:SETVAR WorkDir "C:\scripts\"
--DECLARE TMP FILES
:SETVAR WorkFile "listing.tmp"
:SETVAR RunFile "final_script.txt"
--DELETE PREVIOUS FILE IF EXISTS
!!IF EXIST $(WorkDir)$(RunFile) DEL $(WorkDir)$(RunFile)
!!IF EXIST $(WorkDir)$(WorkFile) DEL $(WorkDir)$(WorkFile)
--REDIRECT OUT TO WORK FILE
:OUT $(WorkDir)$(WorkFile)
--LIST ALL SQL FILES
!!DIR $(WorkDir)"*.sql" /b/o
--APPEND EXECUTE COMMAND
!!FOR /F "usebackq tokens=*" %a in (`dir /b $(WorkDir)*.sql /on`) DO ( @ECHO :r "$(WorkDir)%a">> $(WorkDir)$(RunFile) )
--EXECUTE "final_script"
:r $(WorkDir)$(RunFile)
This script will generate another script, that will contain something like this:
-r: c:\scripts\script_01.sql
-r: c:\scripts\script_02.sql
-r: c:\scripts\script_03.sql
-r: c:\scripts\script_04.sql
The problem that I have is this: I can't find how to automatize the database creation. I'd like to set the database name in this script, and remove any reference to a database name from the path scripts.
I can change this script in order to append the CREATE DATABASE sentence into the final script, in order to have something like this
CREATE DATABASE [MYDB]
GO
USE [MYDB]
GO
-r: c:\scripts\script_01.sql
-r: c:\scripts\script_02.sql
-r: c:\scripts\script_03.sql
-r: c:\scripts\script_04.sql
But, the -r sentences will be executed before the database creation, and the scripts will be executed using [master] database.
If I include or create another script with the database creation sentences, I have no way to tell other scripts which database should use.
Any idea?
Best regards.