iSeries DB2 - 有没有办法从insert语句中选择标识值?

AJ.*_*AJ. 17 sql db2 ibm-midrange

我知道我们很少见,我们这些穷人正在使用iSeries for DB2/AS400,但我希望有人可以回答这个简单的问题.有没有办法在不使用两行SQL的情况下从insert语句返回标识值?我被迫在C#中使用内联SQL来执行插入,然后我需要使用为插入生成的标识.简而言之,我需要iSeries DB2等同于Oracle的"RETURNING".也就是说,

INSERT INTO AwesomeTable (column1, column2, etc.)
    VALUES (value1, value2, etc.)
    RETURNING something;
Run Code Online (Sandbox Code Playgroud)

任何人?提前致谢.

编辑:除非有人知道我可以在一个IBM.Data.DB2.iSeries.iDB2Command(不是存储过程)中执行两行SQL,我想在一行SQL中执行此操作

Ras*_*dit 14

我不确定iSeries,但以下是在db2v8.1上工作的:

考虑"ID"是您的标识列的名称.以下stmt将返回新生成的id(插入stmt插入的id):

SELECT ID FROM FINAL TABLE (
    INSERT INTO AwesomeTable (column1, column2, etc.)
            VALUES (value1, value2, etc.)    
    )
Run Code Online (Sandbox Code Playgroud)

我在publib网站上找到的一些解释:(我用它来参考上面的测试我的查询)

     /* The following SELECT statement references an INSERT statement in its
           FROM clause.  It inserts an employee record from host variables into
           table company_b.  The current employee ID from the cursor is selected
           into the host variable new_id.  The keywords FROM FINAL TABLE
           determine that the value in new_id is the value of ID after the
           INSERT statement is complete.

           Note that the ID column in table company_b is generated and without
           the SELECT statement an additional query would have to be made in
           order to retreive the employee's ID number.
        */
        EXEC SQL SELECT ID INTO :new_id
                 FROM FINAL TABLE(INSERT INTO company_b
                 VALUES(default, :name, :department, :job, :years, :salary, 
                        :benefits, :id));
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助 :)


Vin*_*jip 7

您需要使用IDENTITY_VAL_LOCAL标量函数.从IBM文档:

IDENTITY_VAL_LOCAL 是一个非确定性函数,它返回标识列的最近分配的值.

例:

CREATE TABLE EMPLOYEE
    (EMPNO INTEGER GENERATED ALWAYS AS IDENTITY,
     NAME CHAR(30),
     SALARY DECIMAL(5,2),
     DEPT SMALLINT)

INSERT INTO EMPLOYEE
    (NAME, SALARY, DEPTNO)
    VALUES('Rupert', 989.99, 50)

SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1
Run Code Online (Sandbox Code Playgroud)

  • IDENTITY_VAL_LOCAL()的范围限定为"级别".只要调用存储的proc,触发器或函数,就会创建级别,因此您无需担心其他用户的其他插入. (2认同)