Search code examples
c#sqlsql-serversqlcommandinformation-schema

SQL Check if table Exists in C#, if not create


I think I've seen almost every page relating to this question, most likely answer was Check if a SQL table exists but didn't really understand it. This is what I got:

    private void select_btn_Click(object sender, EventArgs e)
    {
        string theDate = dateTimePicker1.Value.ToString("dd-MM-yyyy");
        SqlConnection SC = new SqlConnection("Data Source=ruudpc;Initial Catalog=leden;Integrated Security=True");
        SqlCommand DateCheck = new SqlCommand("SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '" + theDate + "'");
    }

Now I want a return value from DateCheck.ExecuteScalar(); that can tell me if it exists or not, probably dead simple.

EDIT

Regardless for the sql injection part, and that for some this question is helpful, it is generally bad practice to create tables on the fly, I recommend you reconsider your ERD. Just saying.


Solution

  • Using IF EXISTS T-SQL

    private void select_btn_Click(object sender, EventArgs e)
    {
        string theDate = dateTimePicker1.Value.ToString("dd-MM-yyyy");
    
        // Enclose the connection inside a using statement to close and dispose
        // when you don't need anymore the connection (to free local and server resources)
        using(SqlConnection SC = new SqlConnection("Data Source=ruudpc;Initial Catalog=leden;Integrated Security=True"))
        {
            // Sql command with parameter 
            string cmdText = @"IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES 
                               WHERE TABLE_NAME=@name) SELECT 1 ELSE SELECT 0";
            SC.Open();
            SqlCommand DateCheck = new SqlCommand(cmdText, SC);
    
            // Add the parameter value to the command parameters collection
            DateCheck.Parameters.Add("@name", SqlDbType.NVarChar).Value = theDate
    
            // IF EXISTS returns the SELECT 1 if the table exists or SELECT 0 if not
            int x = Convert.ToInt32(DateCheck.ExecuteScalar());
            if (x == 1)
                MessageBox.Show("Table exists for date " + theDate);
            else
                MessageBox.Show("Table doesn't exist for date " + theDate);
        }
    }