5

I've 2 tables having exactly same columns. But they are stored in Database1 and Database2 (on same server). Can i pass database name as variable? For example:

                        SELECT  [SomeValue]
                        FROM    [Database2].[dbo].[Klienci]

                        SELECT  [SomeValue]
                        FROM    [Database1].[dbo].[Klienci]

Is there a way to pass whole [FROM] as @variable thru following code in C#:

            SqlCommand sqlQuery = new SqlCommand(preparedCommand, varConnection);
            sqlQuery.Prepare();
            sqlQuery.Parameters.AddWithValue("@varDatabase", varDatabase);

Where @varDatabase would hold database name and/or table name ie. [Database1].[dbo].[Klienci] in one format or another.

I'm talking about C# 3.5 / MSSQL 2005/2008.

6 Answers 6

7

Why don't you just set your database when you make the connection? Then the code doesn't even change.

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

1 Comment

Don't know why i haven't thought about that. I already have defined 2 connection strings for 2 databases and i am unnecessary writing FROM [Database2].[dbo].[Klienci] when i could just use FROM [Klienci] since connection string would make the choice for me.
2

It looks you are need to set the database name and the connection string, dynamically, depending upon type of request. Even if you have, say (just for instance) 60 Databases, you might connect to, using hard coded statements is what no one will ever recommend, because

  • It is hard to write
  • It is hard to manage
  • It is hard to update
  • You can use a separate code file for that but it is some thing like reinventing the wheel.

Configuration files serve this purpose, along with many others, and think of your colleagues for a second, looking at this "CustomConnectionStringsFile" and scratching their head.

The best way is to save them as connectionStrings, in your configuration file and use the one you need

Something as this

Adding Connection string to Web.Config

<connectionStrings>
  <add 
    name="NorthwindConnectionString" 
    connectionString="Data Source=serverName;Initial 
    Catalog=Northwind;Persist Security Info=True;User 
    ID=userName;Password=password"
    providerName="System.Data.SqlClient"
  />
  <add 
    name="BestDBConnectionString" 
    connectionString="Data Source=serverName;Initial 
    Catalog= BestDB;Persist Security Info=True;User 
    ID=userName;Password=password"
    providerName="System.Data.SqlClient"
  />
</connectionStrings>

Accessing Connectionstring

    string myConnString ="";
    if(ThisIsThat("A"))
    {
        myConnString = 
                               rootWebConfig.ConnectionStrings.ConnectionStrings["NorthwindConnectionString"];
    }
    else if(ThisIsThat("B"))
    {        
        myConnString =
                                rootWebConfig.ConnectionStrings.ConnectionStrings["BestDBConnectionString"]
    }

    { else // Can go on}

For more info on

Hope it helps

Comments

1

multiple Connections strings are your friend in this case!

Comments

1

No, T-SQL parameters cannot refer to an entity (such as a database or table), if for no other reason than it'd blow the optimizer's mind.

If just the DB name is different, the suggestion of dynamically building the connection string is a good one. You could use the SqlConnectionStringBuilder class to make that less error-prone.

You could also just build up a C# string dynamically, but be careful about opening yourself up to Sql injection attacks.

Otherwise, just do an IF statement in your T-SQL code:

IF (@dbName = 'Database1') BEGIN
   SELECT SomeValue FROM [Database1].[dbo].[Klienci]
END ELSE BEGIN
   SELECT SomeValue FROM [Database2].[dbo].[Klienci]
END

Comments

0

Try something like the DBProviderFactory instead

Comments

0

You can but I would just change the connection to point to the database you want to query.

Clarification:
To clarify, you can do it using dynamic sql. e.g. passing the database name to a sproc which can then build up the complete statement and execute it. Of course, it's invalid to use a variable directly ("SELECT * FROM [@DatabaseName].dbo.TableName" is NOT valid). However, this would not be the recommended approach, hence best thing is to change the connection.

3 Comments

Actually, you can't do what he's doing. No part of an entity identifier in a SQL statement is allowed to be a variable. You could build the statement dynamically, but it cannot be parametrized.
You could, but you'd have to do an exec in the stored proc, which generally defeats the purpose of a stored proc.
@Cade Roux - I know, but you can if you use dynamic sql e.g. I envisaged passing the variable into a sproc, which then builds up the statement dynamically, But I didn't go into that as I don't think it's the right approach

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.