We have an SQL script in a .sql file. It has a couple of parameters defined like this
DECLARE @device_directory NVARCHAR(250) = '$(CONFIG_DBPATH)'+'$(CONFIG_DBNAME)'
We then execute this script in a .bat script:
SET CONFIG_DBNAME=NewConfigBase
SET CONFIG_DBPATH=C:\BT_Server\
sqlcmd -I -S .\SQLEXPRESS8 -i SetUpConfigDb.sql
I've been assigned the task of implementing this functionality as a part of our configuration tool, i.e. creating the physical db file and attaching it to the database. Later, we will also include the creation of database tables, stored procedures, ect, which are currently defined in a separate .sql script.
Ideally, I would like the configuration tool to not rely on sqlcmd, but rather execute the scripts in-process (e.g. by use of SqlCommand). This would allow me to use standard error handling (exceptions) rather than parsing sqlcmd's output.
Now I'm a bit unsure how to tackle this. I want to be able to re-use our existing sql scripts so that we can still use our .bat scripts without maintaining two different sql queries performing the same task.
One of the scripts contains GO on several places. It is my understanding that SqlCommand does not allow this. I am also unsure that I can use SqlParameter to set the value of $(CONFIG_DBPATH) etc (in fact I am almost certain that I can not).
So my question is, what is the recommended way to tackle this scenario? How do I execute .sql commands with GO in them, and how do I specify variables so that the scripts can be used both from .bat files and from managed code? I suppose one option is to 'wash' the script when it's executed from code, to remove GO etc, and modify how variables are handled. But are there any better options?