Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 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);
share|improve this answer
    
Ah, that makes much more sense. Thank you! –  Justin Nov 18 '13 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? –  Justin Nov 18 '13 at 18:05

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.