0

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.

1 Answer 1

1

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);
2
  • Ah, that makes much more sense. Thank you! Commented Nov 18, 2013 at 17:19
  • Actually, while this would work for writing the SQL in the code, we're trying to run a script. So while this answer works in regards to writing the SQL out in the code, I was wondering how it would be done and passed into the script file? Commented Nov 18, 2013 at 18:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.