获取数据库的所有表名

1.使用Connection的GetSchema方法,参数为"Tables"

1
2
3
4
5
6
7
8
9
10
11
12
         public  IList< string > 获取表集合(SqlConnection 连接)
         {
             List< string > 表名 =  new  List< string >();
             DataTable dt = 连接.GetSchema( "Tables" );
             foreach  (DataRow row  in  dt.Rows)
             {
                 string  表类型 = ( string )row[ "TABLE_TYPE" ];
                 if  (表类型.Contains( "TABLE" ))
                 { 表名.Add(row[ "TABLE_NAME" ].ToString()); }
             }
             return  表名;
         }

2.使用SELECT语句针对系统表进行操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
         public  IList< string > 获取表集合2(SqlConnection 连接)
         {
             SqlCommand 命令 =  new  SqlCommand
             ( @"SELECT name FROM sysobjects WHERE (OBJECTPROPERTY(id, N'IsUserTable') = 1)" , 连接);
             List< string > 表名 =  new  List< string >();
             SqlDataReader 读取器 = 命令.ExecuteReader();
             while  (读取器.Read())
             {
                 string  名称 = 读取器[0].ToString();
                 表名.Add(名称);
             }
             读取器.Close();
             return  表名;
         }

猜你喜欢

转载自blog.csdn.net/aila852/article/details/79986494