如何检查SQL Server CE 3.5中是否存在表

我在asp.net中有一个数据库user.sdf ,我想创建表,我需要检查它检查它先存在不存在然后不需要创建表,否则创建新表如何检查它请帮我解决这个问题。

您可以在SQL CE 3.5中查询架构视图,看看这里 。

这是一个可以使用的简单扩展方法。

 public static class SqlCeExtentions { public static bool TableExists(this SqlCeConnection connection, string tableName) { if (tableName == null) throw new ArgumentNullException("tableName"); if (string.IsNullOrWhiteSpace(tableName)) throw new ArgumentException("Invalid table name"); if (connection == null) throw new ArgumentNullException("connection"); if (connection.State != ConnectionState.Open) { throw new InvalidOperationException("TableExists requires an open and available Connection. The connection's current state is " + connection.State); } using (SqlCeCommand command = connection.CreateCommand()) { command.CommandType = CommandType.Text; command.CommandText = "SELECT 1 FROM Information_Schema.Tables WHERE TABLE_NAME = @tableName"; command.Parameters.AddWithValue("tableName", tableName); object result = command.ExecuteScalar(); return result != null; } } } 

您可以按如下方式使用上述内容

 using (SqlCeConnection connection = new SqlCeConnection(@"Data Source=MyDatabase1.sdf")) { connection.Open(); if (connection.TableExists("MyTable")) { // The table exists } else { // The table does not exist } } 

作为替代方案,您可以查询表并捕获抛出的exception。 如果存在exception,则找不到表,否则表存在。

 SELECT TOP 1 1 FROM TableName; 

一个简单而简单的性能测试比针对INFORMATION_SCHEMA的查询具有更好的结果。 虽然我认为对INFORMATION_SCHEMA的查询更清晰。