当我的.sdf
文件中只有一个表时,这段代码运行良好:
const string sdfPath = @"\Program Files\duckbilled\Platypus.sdf";
string dataSource = string.Format("Data Source={0}", sdfPath);
if (!File.Exists(sdfPath))
{
using (var engine = new SqlCeEngine(dataSource))
{
engine.CreateDatabase();
}
using (var connection = new SqlCeConnection(dataSource))
{
connection.Open();
using (var command = new SqlCeCommand())
{
command.Connection = connection;
command.CommandText =
"CREATE TABLE Platydudes (Id int NOT NULL, BillSize smallint NOT NULL, Description nvarchar(255)";
command.ExecuteNonQuery();
}
}
}
...但现在我需要知道的不是数据库文件 ( ) 是否存在,而是该表/文件中Platypus.sdf
是否存在特定表(例如)。Platydudes
有没有办法确定?
更新
查询中的“IF NOT EXISTS”子句会导致运行时异常。这段代码:
using (var connection = new SqlCeConnection(dataSource))
{
connection.Open();
using (var command = new SqlCeCommand())
{
command.Connection = connection;
command.CommandText = "IF NOT EXISTS( SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'InventoryItems') " +
"CREATE TABLE InventoryItems (Id nvarchar(50) NOT NULL, PackSize smallint NOT NULL, Description nvarchar(255), DeptDotSubdept numeric, UnitCost numeric, UnitList numeric, UPCCode nvarchar(50), UPCPackSize smallint, CRVId int);";
command.ExecuteNonQuery();
}
}
...导致抛出此异常:解析查询时出错。[令牌行号 = 1,令牌行偏移量 = 1,错误令牌 = IF]
因此,查询解析器显然不需要“IF”业务。如果表不存在,是否有另一种方法只创建表?还是我应该每次都先删除表然后重新创建它?IOW,我应该这样做:
using (var connection = new SqlCeConnection(dataSource))
{
connection.Open();
using (var command = new SqlCeCommand())
{
command.Connection = connection;
command.CommandText = "DELETE InventoryItems";
command.ExecuteNonQuery();
}
using (var command = new SqlCeCommand())
{
command.Connection = connection;
command.CommandText = "CREATE TABLE InventoryItems (Id nvarchar(50) NOT NULL, PackSize smallint NOT NULL, Description nvarchar(255), DeptDotSubdept numeric, UnitCost numeric, UnitList numeric, UPCCode nvarchar(50), UPCPackSize smallint, CRVId int);";
command.ExecuteNonQuery();
}
}
?
更新 2
在第一次更新中回答我上面的问题:不!如果我这样做,我会在第二次调用 .ExecuteNonQuery()时得到“指定的表已经存在”。
更新 3
回应湿婆对我的回答的评论:
这(重用命令对象)以同样的方式失败(“表已经存在”):
using (var command = new SqlCeCommand())
{
command.Connection = connection;
command.CommandText = "DELETE InventoryItems";
command.ExecuteNonQuery();
command.CommandText = "CREATE TABLE InventoryItems (Id nvarchar(50) NOT NULL, PackSize smallint NOT NULL, Description nvarchar(255), DeptDotSubdept numeric, UnitCost numeric, UnitList numeric, UPCCode nvarchar(50), UPCPackSize smallint, CRVId int);";
command.ExecuteNonQuery();
}