Question

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?

Was it helpful?

Solution

If you want to execute sql scripts via sqlcommand programmatically, then you need to open the file and read it line by line. As you pass each line, append it to the current batch string builder and when you hit a line that after trimming is GO, get string builder ToString and execute that batch. Clear the current batch and keep going.

edit: second part of question As far as the parameters go, you can either replace them as part of parsing and executing or you could pull duties like creating the DBs out to C# code. As a preference, I've always kept the sql scripts runnable by ssms and sqlcmd by developers even though they happen to be run by C# code as part of the deployment. So that means, I wouldn't make up any special tokens that only your code understands. You could leave as is in your question, replace them and above that in the script, have the variables declared and commented out with -- so developers can easily work in ssms.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top