Information such as table names for SQL Server databases is part of the schema collection, ADO. The SqlConnection class in net contains a GetSchema method for getting a list of supported schema collections, so to determine whether a table exists in a SQL Server database, you can Sqlconnection.getschema ("Tables") to obtain, the method returns a DataTablewith Table_catalog, Table_ in theDataTable Schema, TABLE_NAME, TABLE_TYPE, and so on 4 columns, thetable_name column is the data table name.
The sample code is as follows:
usingSystem;usingSystem.Data;usingSystem.Data.SqlClient;namespacescratchline.cn{ Public classTable { PublicTable () {}/// <summary> ///determine if a table named TableName exists in the database/// </summary> /// <param name= "TableName" >the name of the table to query</param> /// <param name= "connectionString" >Database connection String</param> /// <returns></returns> Public BOOLExist (stringTableName,stringconnectionString) { BOOLBexist =false; SqlConnection _connection=NewSqlConnection (connectionString); Try{_connection.open (); using(DataTable dt = _connection.getschema ("Tables")) { foreach(DataRow Drinchdt. Rows) {if(string. Equals (TableName, dr[2]. ToString ())) {Bexist=true; Break; } } } } Catch(Exception ex) {Throwex; } finally{_connection.dispose (); } returnbexist; } }}
View Code
To learn more about the SQL Server schema collection, refer to the official documentation: https://msdn.microsoft.com/zh-cn/library/ms254969 (v=vs.100). aspx
How C # Determines whether a data table exists in SQL Server