有没有一种方法来检查表是否存在,而不选择和检查它的值?

也就是说,我知道我可以去SELECT testcol FROM testtable并检查返回字段的计数,但似乎必须有一个更直接/优雅的方式来做到这一点。


当前回答

你可以这样做:

            string strCheck = "SHOW TABLES LIKE \'tableName\'";
            cmd = new MySqlCommand(strCheck, connection);
            if (connection.State == ConnectionState.Closed)
            {
                connection.Open();
            }
            cmd.Prepare();
            var reader = cmd.ExecuteReader();
            if (reader.HasRows)
            {                             
              Console.WriteLine("Table Exist!");
            }
            else
            {                             
              Console.WriteLine("Table does not Exist!");
            }

其他回答

只是添加一个额外的方法来做它,这取决于你需要它的原因,你可以使用一个处理er_no_such_table错误:1146的处理程序,如下所示:

DELIMITER ;;
CREATE PROCEDURE `insert_in_my_table`(in my_var INT)
BEGIN
   -- Error number for table not found
   DECLARE CONTINUE HANDLER FOR 1146
   BEGIN
      -- table doesn't exists, do something...
      CREATE TABLE my_table(n INT);
      INSERT INTO my_table (n) values(my_var);
   END;
      -- table does exists, do something...
      INSERT INTO my_table (n) values(my_var);
END ;;
DELIMITER ;

下面是一个不是SELECT * FROM的表

SHOW TABLES FROM `db` LIKE 'tablename'; //zero rows = not exist

这是从一个数据库专家那里得到的,这是我被告知的:

select 1 from `tablename`; //avoids a function call
select * from INFORMATION_SCHEMA.tables where schema = 'db' and table = 'table' // slow. Field names not accurate
SHOW TABLES FROM `db` LIKE 'tablename'; //zero rows = does not exist

在创建TABLE之前,最好先检查SQL Server数据库中是否存在该表。

USE [DB_NAME]
GO
IF OBJECT_ID('table_name', 'U') IS NOT NULL
BEGIN
PRINT 'Table exists.'
END
ELSE
BEGIN
PRINT 'Table does not exist.'
END

另外 使用sys。对象,检查SQL Server中是否存在表。

USE [DB_NAME]
GO
IF EXISTS(SELECT 1 FROM sys.Objects
WHERE Object_id = OBJECT_ID(N'table_name')
AND Type = N'U')
BEGIN
PRINT 'Table exists.'
END
ELSE
BEGIN
PRINT 'Table does not exist.'
END

如果想要正确,请使用INFORMATION_SCHEMA。

SELECT * 
FROM information_schema.tables
WHERE table_schema = 'yourdb' 
    AND table_name = 'testtable'
LIMIT 1;

或者,您也可以使用SHOW TABLES

SHOW TABLES LIKE 'yourtable';

如果结果集中有行,则表存在。

性能比较:

MySQL 5.0.77,在一个大约有11000个表的数据库上。 选择一个非最近使用的表,这样它就不会被缓存。 平均每次超过10次。(注意:做不同的表,以避免缓存)。

322ms:显示'table201608'这样的表;

select 1 from table201608 limit 1;

319ms: SELECT count(*) FROM information_schema。table WHERE (TABLE_SCHEMA = 'mydb') AND (TABLE_NAME = 'table201608');

注意,如果你经常运行这个,比如在短时间内处理很多HTML请求,第2个会更快,因为它平均缓存200毫秒或更快。