如何使用C#和DB2获取最后插入的记录ID

时间:2018-11-16 00:19:59

标签: c# db2

在我的应用程序中将C#与DB2一起使用。想要获取最后插入的记录ID以传递另一个SQL语句。请在下面找到我的代码:

        DB2Command myCommand = new DB2Command();
    DB2Connection con = new DB2Connection(ConnectionString);
    myCommand.Connection = con;

    try
    {
        myCommand.CommandType = CommandType.Text;
        myCommand.CommandText = "SELECT ID FROM FINAL TABLE (INSERT INTO MyTable(col1,col2) "
               + " VALUES (val1, val2)";


        con.Open();
        lastInstertedId = myCommand.ExecuteNonQuery();
    }

但是它抛出错误:

  

该操作失败,因为指定的表的类型不支持该操作。

如果我将CommandText更改为给定行以下,则它可以正常工作,但会改写1(影响行号)。

myCommand.CommandText = "INSERT INTO MyTable(col1,col2) "
           + " VALUES (val1, val2)";

请让我知道如何获取最后插入的记录ID。

3 个答案:

答案 0 :(得分:0)

我认为sql应该是:

 myCommand.CommandText = "SELECT ID FROM NEW TABLE (INSERT INTO MyTable(col1,col2) "
           + " VALUES (val1, val2)";
  

我们在DB2中所做的只是在从句中简单地公开了触发器转换表NEW TABLE。   因此,当您将INSERT语句放入from子句中时,将执行insert语句,并在此过程中生成转换表。   然后可以查询该转换表,其中包括对触发器之前的所有修改。

https://www.ibm.com/developerworks/community/blogs/SQLTips4DB2LUW/entry/select_from_insert?lang=en

通知FINAL已由NEW

取代

答案 1 :(得分:0)

应该如下所示。

DB2Command myCommand = new DB2Command();
DB2Connection con = new DB2Connection(ConnectionString);
myCommand.Connection = con;

try
{
    myCommand.CommandType = CommandType.Text;
    myCommand.CommandText = "SELECT ID FROM FINAL TABLE (INSERT INTO MyTable(col1,col2) "
           + " VALUES (val1, val2)";
    Integer lastInstertedId = (Integer)myCommand.ExecuteScalar();
}

答案 2 :(得分:0)

我假设您的表是ORGANIZE BY COLUMN。这些表格目前不支持data-change-table-reference

$ db2 "create table m(i int) organize by column"
DB20000I  The SQL command completed successfully.

$ db2 "select * from final table(insert into m values 1)"
SQL1667N  The operation failed because the operation is not supported with the 
type of the specified table.  Specified table: "PAUL.M".  Table type: 
"ORGANIZE BY COLUMN".  Operation: "FINAL|NEW|OLD TABLE".  SQLSTATE=42858

$ db2 "create table m(i int) organize by row"
DB20000I  The SQL command completed successfully.

$ db2 "select * from final table(insert into m values 1)"

I          
-----------
          1

  1 record(s) selected.