How C # Determines whether a data table exists in SQL Server

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.