on 2017 Mar 13 7:57 AM
I have the following Stored Procedure that works fine,
ALTER PROCEDURE "DBA"."New-Project" @creator varchar(3), @project varchar(40), @gutt integer, @cdate date AS INSERT INTO dba.lead (leadno, contno, leadsrccd, leaddate, createdby, leadsttscd, cg_code, leadsizecd, guttometer, estclose, lead_desc) VALUES (getNextPrimary('lead'), 2036, 'DASHB', today(), @creator, 'QUOTE', 777, 'RF', @gutt, @cdate, @project)
What I would like to do is get the new 'leadno'
that is created once the stored procedure has run. I have seen several references to @@identity
, but I am not sure if this is what I should be using and if so how to use it? As currently I just get 0.
In order to use the @@identity global variable, you need to insert a new record without supplying a value for the PK column declared with DEFAULT (GLOBAL) AUTOINCREMENT - to cite the docs:
The @@identity variable holds the most recent value inserted by the current connection into an IDENTITY column, a DEFAULT AUTOINCREMENT column, or a DEFAULT GLOBAL AUTOINCREMENT column, or zero if the most recent insert was into a table that had no such column.
In your case, you do supply a value via the function "getNextPrimary('lead')", so @@identity will return 0.
When the "leadno" PK column is declared with DEFAULT AUTOINCREMENT, you can simply omit the column in the INSERT column (or supply the special DEFAULT value for it), and then @@identity will return the automatically generated value, such as:
BEGIN INSERT INTO dba.lead (contno, leadsrccd, leaddate, createdby, leadsttscd, cg_code, leadsizecd, guttometer, estclose, lead_desc) VALUES (2036, 'DASHB', today(), @creator, 'QUOTE', 777, 'RF', @gutt, @cdate, @project); SELECT @@identity; END;
Note: You can also use the builtin get_identity() function to let the server create the next value beforehand, i.e. you probably could replace your
getNextPrimary('lead')
call with
get_identity('lead')
in order to use a builtin function.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Amazingly enough, you CAN specify get_identity() in the VALUES clause and it will fill @@IDENTITY...
CREATE TABLE t ( pkey INTEGER NOT NULL DEFAULT AUTOINCREMENT PRIMARY KEY, data INTEGER NOT NULL ); INSERT t ( data ) VALUES ( 111 ); COMMIT; SELECT '@@IDENTITY # 1', @@IDENTITY; '@@IDENTITY # 1',@@IDENTITY '@@IDENTITY # 1',1 INSERT t ( pkey, data ) VALUES ( GET_IDENTITY ( 't' ), 111 ); COMMIT; SELECT '@@IDENTITY # 2', @@IDENTITY; '@@IDENTITY # 2',@@IDENTITY '@@IDENTITY # 2',2
User | Count |
---|---|
67 | |
10 | |
10 | |
10 | |
10 | |
8 | |
8 | |
7 | |
5 | |
5 |
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.