mynkow
mynkow

Reputation: 4548

How to pass $(DB) parameter to SqlCommand?

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?

Upvotes: 0

Views: 819

Answers (2)

Иван Вълчев
Иван Вълчев

Reputation: 131

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

Upvotes: 2

Void
Void

Reputation: 265

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...

Upvotes: 0

Related Questions