I have my SQL Server connection string set up like this:
String strConnection = @"Data Source=servername;Initial Catalog=dbname; User ID =user; Password =pass;";
Then I have a combobox which shows all tables in that database. Connection string works fine with one database (initial catalog). But what if I want to pull tables from 2 databases on the same server. User in SQL Server has access to both databases. What connection string do I use then?
The easy way would be Initial Catalog=dbname,db2name
. But that does not work of course.
4条答案
按热度按时间omqzjyyz1#
If that user does have in fact permissions to access the other database - you could just simply use the
ChangeDatabase
method on yourSqlConnection
- like this:wlp8pajw2#
Edit Start
If you want to show all the tables in all the data bases please populate the combo box the same. refer: How do I list all tables in all databases in SQL Server in a single result set?
Or you can provide another combo box to display list of data bases, prior to tables combo box, once user chooses a DB name, pass it to the query. This is useful choice, as there is a possibility of having a table with same name in two data bases. (Eg: t_users in db_1 and db_2)
If you have confined to two data bases, use where clause in the above said (1)
Edit end
If you want to access multiple data bases of one server and one instance, It is enough to have one connection to one database in that server and instance, provided user has access to those DBs. You can query any data base if all DB are in same server and instance, see example below.
In your case, you can have your query of stored procedure similar to below queries.
evrscar23#
I ended up using two comboboxes on my form. One for databases and one for tables. When i choose a database in first combobox, the second one automaticly shows tabels in that database. It is much easier for me to work wit two comboboxes using different connections. Here is some part of my code with solution:
8gsdolmq4#
I'm late to the party, but as @Surendra touched on, you can use a stored procedure to query multiple databases (even on different servers using linked servers). To return a single data set, you can use 'union'.