Passing database name as variable to SQL from C#. Is it possible?

ado.net, c#, sql, sql-server-2005, sql-server-2008

Solution

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

Problem

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.

Original source