SQL检查表是否存在于C#中,如果不存在则创建

时间:2014-04-14 17:36:17

标签: c# sql sql-server sqlcommand information-schema

我想我几乎看到了与这个问题相关的每一页,最有可能的回答是 Check if a SQL table exists 但并没有真正理解它。这就是我得到的:

    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 + "'");
    }

现在我想要DateCheck.ExecuteScalar()的返回值;可以告诉我它是否存在,可能很简单。

修改

无论是sql注入部分,对于某些人来说这个问题是有用的,通常不好的做法是动态创建表,我建议你重新考虑你的ERD。只是说。

2 个答案:

答案 0 :(得分:7)

使用IF EXISTS T-SQL

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

    string cmdText = @"IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES 
                       WHERE TABLE_NAME='" + theDate + "') SELECT 1 ELSE SELECT 0";
    SC.Open();
    SqlCommand DateCheck = new SqlCommand(cmdText, SC);
    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);
    SC.Close();
}

答案 1 :(得分:2)

编写代码的方式可能导致sql注入攻击。参数化的SQL语句是一种避免SQL注入攻击的简单方法,也是一种很好的编码实践

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#代码

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