Question

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.

Was it helpful?

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);
    }
}

OTHER TIPS

The way you write the code can lead to sql injection attack.Parameterized SQL statements are an easy way to avoid SQL injection attacks and also a good codding practise

CREATE PROCEDURE checkTableExist
@theDate  varchar(10)
AS 
SET NOCOUNT ON;
IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME=@theDate) SELECT 1     ELSE SELECT 0

C# code

  try
  {     
     string theDate = dateTimePicker1.Value.ToString("dd-MM-yyyy");    
     sqlConnection = new SqlConnection(dbConnectionString);
     SqlCommand command = new SqlCommand("checkTableExist", sqlConnection);
     command.CommandType = CommandType.StoredProcedure;
     command.Parameters.Add("@theDate", SqlDbType.VarChar).Value = dateTimePicker1.Value.ToString("dd-MM-yyyy");
     sqlConnection.Open();
     int result = (Int32)command.ExecuteScalar();
     sqlConnection.Close();

     if (result == 1)
     return true;//or any message 
     else
     return false;    
  }
catch (SqlException ex)
  {
     Console.WriteLine("SQL Error" + ex.Message.ToString());
     return false;
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top