开发者

DbConnection.GetSchema("Tables") returns tables only for one database

开发者 https://www.devze.com 2023-03-31 18:14 出处:网络
I try to get all table names for all databases. But GetSchema(\"Tables\") returns names only for one db.

I try to get all table names for all databases. But GetSchema("Tables") returns names only for one db. It's strange cause I use开发者_如何学Go no restrictions and have dbowner on many dbs with read/write permissions.

What do I need to get all tables info?


It would only return the list of tables in the current context's database. To get a list of all the tables you'll need to loop through each database.

I have used it in one of my open source projects - http://dbdoc.codeplex.com

You'll have to do something like this:

foreach (Microsoft.SqlServer.Management.Smo.Database db in server.Databases)
 foreach (Microsoft.SqlServer.Management.Smo.Table tbl in db.Tables)
                        tables.Add(tbl.Name);  // Temp variable


I made it this way:

Cursor.Current = Cursors.WaitCursor;
                            sqlConnection.Open();
                            System.Data.DataTable dataTable = sqlConnection.GetSchema("Databases");

                            foreach (System.Data.DataRow row in dataTable.Rows)
                            {
                                using (var tablesConnection = new System.Data.SqlClient.SqlConnection())
                                {
                                    var dbName = row[0] as string;
                                    try
                                    {
                                        sqlConnection.ChangeDatabase(dbName);
                                    }
                                    catch (Exception)
                                    {
                                        continue;
                                    }

                                    var tables = sqlConnection.GetSchema("Tables");
                            }

The real issue is that even initial catalog is not specified explicitly default db is assigned. So GetSchema("Tables") shoul be called for every db on the server. It may be other db, not necessarily 'master'. And I thought GetSchema("Tables") returns all tables for all databases.

0

精彩评论

暂无评论...
验证码 换一张
取 消