在SQL Compact Edition中的事务中,@@ IDENTITY返回NULL

时间:2013-01-09 19:04:44

标签: c# sql-server-ce

我有一个SQL Server Compact Edition数据库,其中包含3列的表:IdField1Field2IdIDENTITY(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中不受支持。

如何检索插入的标识值?有没有解决这个问题的解决方法?

2 个答案:

答案 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;