Justin
Justin

Reputation: 35

Using a Variable for DB Name in SQL Script, Running it from C#

I have script that needs to be run from a console application but the Database name will be whatever is in the app.config. I've been researching using variables in scripts and passing them in from C# but I can't seem to find much info on using a variable for the DB name since it will be coming from app.config connection string (the application will be used at multiple sites). If I try to do something like

DECLARE @dbName CHAR(50)
USE @dbName 

and try to do a query it gives me an error on @dbname. Something like incorrect syntax, expecting ID or QUOTED_ID.

Is there a way to accomplish what I am trying to do?

EDIT: While the below answer takes care of the question regarding writing out SQL in the code, I was looking for a solution in regards to passing in a variable from C# into an SQL Script that I am running. Or why I get an error when trying to use a variable for the database name.

EDIT 2: I ended up using the placeholder @DATABASENAME in the script file and then read it into a string. After the string was populated I replaced @DATABASENAME with the name of the database being targeted.

Upvotes: 0

Views: 446

Answers (1)

Mike Monge
Mike Monge

Reputation: 66

Do you need to have the database name in a variable? Why not just pass it into the Use directy?

string databaseVariable = "MASTER";
string sql = "USE {0}";
sql = string.Format(sql, databaseVariable);
RunSql(sql);

Upvotes: 1

Related Questions