0

I have the following query:

use [$(DB)]
select * from users

but I cannot pass the parameter trough SqlCommand. It works only from the command line tool. It says that $DB database does not exist, so the parameter is not passed.

            SqlCommand cmd = new SqlCommand(query, connection);
            cmd.Parameters.AddWithValue("DB", "theDatabase");
            cmd.ExecuteNonQuery();

Any ideas?

4
  • 3
    Why not specify the DB in your connection string? Commented Feb 21, 2012 at 15:55
  • These are migration scripts which are hundreds of hundreds. MSSQLSERVER 2005 and 2008 Commented Feb 21, 2012 at 15:59
  • mynkow if these are migration scripts the you should be able to determine what DB each script is working off of.. also what ever script or batch process that is doing it now.. as a temporary work around .. could you now create a console app that spawns or Creates that Process which calls the code at hand use [$DB] select * from users..? Commented Feb 21, 2012 at 16:05
  • At the moment all scripts are executed from very old application which uses sql command line tool. We are trying to refactor that application. Yes, I can. Commented Feb 21, 2012 at 18:39

2 Answers 2

2

SQLCMD has its own commands, which it parses separately from SQL/T-SQL statements. These commands are not understood by SQL Server or other scripting tools like SSMS

http://sqlblog.com/blogs/michael_coles/archive/2010/01/10/parent-child-build-scripts-with-sqlcmd.aspx

Sign up to request clarification or add additional context in comments.

Comments

0

The only way I can think of doing that is ti use exec to like this:

exec ('use ['+ @db + ']; SELECT * FROM someTable');

I'm not sure if this will help you but...

Comments

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.