我有一个SQL Server Compact Edition数据库,其中包含3列的表:Id
,Field1
和Field2
。 Id
为IDENTITY(1,1) NOT NULL
。
const string SQL_INSERT = @"INSERT INTO Table(Field1, Field2) VALUES(@Param1, @Param2)";
const string SQL_SELECT_IDENTITY = @"SELECT @@IDENTITY AS ID";
SqlCeConnection cn = null;
SqlCeTransaction tr = null;
SqlCeCommand cm = null;
try
{
cn = Utility.GetConnection();
cn.Open();
tr = cn.BeginTransaction();
cm = new SqlCeCommand(SQL_INSERT, cn);
cm.Transaction = tr;
cm.Parameters.AddWithValue("@Param1", data.Data1);
cm.Parameters.AddWithValue("@Param2", (int)data.Data2);
cm.ExecuteNonQuery();
cm = new SqlCeCommand(SQL_SELECT_IDENTITY, cn);
object o = cm.ExecuteScalar();
data.Id = Convert.ToInt32(o);
// other operations
}
问题是cm.ExecuteScalar()
返回null。如果我删除该事务,查询将返回适当的值。使用SCOPE_IDENTITY()
失败,因为它在SQL Server CE中不受支持。
如何检索插入的标识值?有没有解决这个问题的解决方法?
答案 0 :(得分:3)
我刚刚意识到原因,身份选择也需要使用交易。
cm = new SqlCeCommand(SQL_SELECT_IDENTITY, cn);
// ADD THE TRANSACTION TO THE COMMAND
cm.Transaction = tr;
// ----------------------------------
object o = cm.ExecuteScalar();
data.Id = Convert.ToInt32(o);
答案 1 :(得分:0)
cm = new SqlCeCommand(SQL_SELECT_IDENTITY, cn);
object o = cm.ExecuteScalar();
data.Id = Convert.ToInt32(o);
用这个:
cm.CommandText = "SELECT @@IDENTITY";
var id = cm.ExecuteScalar();
tr = cn.BeginTransaction(); cm.Transaction = tr;