当表有0行时,如何检查数据库表是否存在?

时间:2019-01-28 14:04:24

标签: c# sql-server database datareader

编辑:很抱歉浪费大家的时间,下面的代码显示我在更正它后可以正常工作,但忘记了PMS_CALC_SCHEDULE上的'C'。

在下面的代码中,如果表存在于数据库中,则“ exist”应== 1。但是,即使表存在于数据库中,它也会为我返回0。我不确定为什么会这样吗?

谢谢:

foreach (var row in calcSched)
            {
                var dif3 = new DataInterfaceFactory(DatabaseTypes.SqlServer, row.DatabaseName, row.ServerName);

                using (DataReader dr2 = dif3.GetDataReader())
                {
                    dr2.ExecuteReader("SELECT COUNT(1) AS TABLECOUNT2 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'PMS_CAL_SCHEDULE'");
                    var exists = Convert.ToInt32(dr2["TABLECOUNT2"]);
                    CommandExecutor CE = dif3.GetCommandExecutor();

                    try
                    {
                        if (exists == 0)//if table doesn't exist create it
                        {
                            string sql = "CREATE TABLE dbo.PMS_CAL_SCHEDULE(CALCULATION_SCHEDULE_UID INT, USER_UID INT, SCHEDULE_DATE DATE, PMS_CALC_STATUS_UID INT, CALCULATION_START_DATE DATE, CALCULATION_END_DATE DATE, STATUS_MESSAGE CHAR(100), PROGRESS CHAR(20)";
                            CE.ExecuteNonQuery(sql);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error: could not create PMS_CALC_SCHEDULE");
                    }
                }
            }

2 个答案:

答案 0 :(得分:1)

您正在使用ExecuteReader,然后尝试不首先执行dr2.Read()而访问其中的数据。

答案 1 :(得分:-2)

据我了解,这是MS SQL Server。您可以直接查询sys.tables。即:

select case when exists ( select  *
                from    sys.tables
                where   [name] = 'YourTableName'
                        and is_ms_shipped = 0 )  then 1 else 0 end;

此外,您可以直接在连接上使用GetSchema查询。即:

void Main()
{
  string strCon =
      @"server=.\sqlexpress;database=Northwind;Trusted_connection=yes";
  DataTable schemaInfo;    
  string[] restrictions = {"Northwind",null,null,"BASE TABLE"};

  using( SqlConnection con = new SqlConnection(strCon))
  {
   con.Open();
   schemaInfo = con.GetSchema("Tables", restrictions );
   con.Close();
  }
  // schemaInfo datatable contains all tables
}

PS:您误导了人们,好像它是一种检查MS SQL Server中表是否存在的方式,从而导致某些人不赞成使用正确的方式。