【问题标题】:Select SCOPE_IDENTITY after insert with SqlCeCommand使用 SqlCeCommand 插入后选择 SCOPE_IDENTITY
【发布时间】:2016-11-14 17:59:41
【问题描述】:

我的程序有在线和离线模式。

  • 它使用 C# SqlCommand 类在线连接到 SQL Server 实例。
  • 离线它使用 C# SqlCeCommand 类连接到本地 .SDF 文件。

现在我想在在线模式下执行以下操作

GetSqlCommand("insert into my_table (col1) values (@c1); SELECT SCOPE_IDENTITY()", conn))

所以我插入一条记录,然后用SELECT SCOPE_IDENTITY() 取回该新记录的 ID。

但在使用 SQL Server CE 处于脱机模式时,它会引发错误。有没有办法在不运行单独查询的情况下使用 SQL Server CE 从插入中取回 ID?

【问题讨论】:

    标签: c# sql sql-server sql-server-ce


    【解决方案1】:

    SQL Server CE 不支持单个命令中的多个查询,尝试如下

    SqlCeCommand  cmd = new SqlCeCommand("insert into my_table (col1) values (@c1)", conn);
    //set paremeter values 
    //execute insert 
    cmd.ExecuteNonQuery();
    //now change the sql statment to take identity 
    cmd.CommandText = "SELECT @@IDENTITY";
    int id = Convert.ToInt32(cmd.ExecuteScalar());
    

    https://stackoverflow.com/a/6480017/2558060

    【讨论】:

      【解决方案2】:

      我认为这是你的答案: How do I use an INSERT statement's OUTPUT clause to get the identity value? 但我不确定 SQL CE.. 试试看。

      编辑: 那么这个答案大概是对的:Inserting into SQL Server CE database file and return inserted id

      【讨论】:

      【解决方案3】:

      虽然 Damith 的回答是正确的,但是我们不能使用 SQL Server CE 运行多个查询。

      我以相同的代码为例。

          SqlCeCommand  cmd = new SqlCeCommand("insert into my_table (col1) values (@c1)", conn);
          //set paremeter values 
          //execute insert 
          cmd.ExecuteNonQuery();
          //now change the sql statment to take identity 
          ////////////////**CONNECTION SHOULD NOT BE CLOSED BETWEEN TWO COMMANDS**/////
          cmd.CommandText = "SELECT @@IDENTITY";
          int id = Convert.ToInt32(cmd.ExecuteScalar());
      

      注意:两个命令之间应该打开连接,否则第二个查询会失败。

      最好在事务中使用此代码。

      注意:SQL Server CE 对象不是线程安全的,如果SqlCeConnectionSqlCeTransaction 的实例在线程间共享,可能会导致访问冲突异常。建议每个线程应该使用一个单独的连接,它不应该被多个线程共享。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-03
        • 1970-01-01
        • 2016-04-28
        • 1970-01-01
        相关资源
        最近更新 更多