get auto increment in query as a variable to use in another query - sql

I am inserting into two tables. Into the first table goes a new 'item'. There are a lot of fields, but for simplicity I'll only show you what I need. This is my coldfusion page:
<cfquery>
INSERT INTO my_item_table (itemid, a bunch of other stuff)
VALUES (itemid_sequence.nextval, a bunch of other stuff)
</cfquery>
My issue is I want to insert that auto-incremented itemid as a value into another table, a file-attachment table. The same coldfusion page:
<cfquery>
INSERT INTO my_attachments_table (attachno, itemid, filename)
VALUES (attachment_sequence.nextval, **AUTO-INCREMENT VALUE HERE**, '#url.fileName#')
</cfquery>
I know I could query the item table for the values that were just entered into the first table, but even though it's not likely, there is a possibility that the user input isn't unique, meaning a query of the same fields could return more than one row. In which case, I couldn't get the itemid. The itemid created in the query is the only unique identifier.
My question is: is there a way to set the auto=increment to a value inside the query so I can use it outside? If not, how would you suggest getting my itemid? Thanks.

If you do an insert via in ColdFusion 8/9/10, it returns the ID of the inserted row (or rows) in the result attribute of the tag. For example, if you're using SQL Server, result_name.IDENTITYCOL is the reference to the ID of the inserted row. If you're using MySQL, it's result_name.GENERATED_KEY.

You could start by retrieving the next sequence value into a variable with a query like this:
SELECT itemid_sequence.nextval FROM DUAL
(DUAL is a dummy table in Oracle). You could then proceed to use this variable in both INSERT queries.
Another option: create a stored procedure in the database that will fire both queries for you.

Related

primary key of newly added row in sql table, vb.net

I have a vb.net application where datagridview is databound to sql table at design time(with table adapter and dataset). All I wanted is to get newly added row's Primary key(int) when i add new row to it. I have searched, but it's showing sql commands like below:
INSERT INTO #Customers
(Name)
VALUES ('Customer 1')
SELECT SCOPE_IDENTITY()
so using scope_identity(). But is there any way I can do it with adapter(or dataset) in vb.net or same command can be given though adapter or similar ?
Thanks in advance!
try this!
SCOPE_IDENTITY() will give you the last identity value inserted into any table directly within the current scope (scope = batch, stored procedure, etc. but not within, say, a trigger that was fired by the current scope)
Use the OUTPUT clause if you are inserting multiple rows and need to retrieve the set of IDs that were generated.
INSERT #a(x) OUTPUT inserted.identity_column VALUES('b'),('c');
--
result will be
1
2

Get ID of autoincrement field in SQLite

I'm using SQLite database.
I want make an insert and get the field ID (autogenerated) of this insert.
The field ID is an autoincrement key.
I'm using the statement
SELECT last_insert_rowid();
and this works fine.
The problem is when I have many concurrent insert into the table: in this case it possible it returns me an ID associated to another insert (not my insert).
What can I do, for making the operation in autonoumus manner?
From the SQLite documentation;
The last_insert_rowid() function returns the ROWID of the last row
insert from the database connection which invoked the function.
So, as long as you're calling the select on the same connection right after you did the insert, other simultaneous users are entirely independent and won't cause the returned value to be wrong.

SQL: is it possible to combine an INSERT and SELECT statement into one

I want to add a row using SQLs INSERT statement. Is it possible that as part of this statement I can somehow get the value of the column userId which I don't update but is the AUTO_INCREMENT primary key. I need this value to update another table, however I can't follow the Insert statement immediately with a SELECT statement as there is no other unique identifier in the table on which to select.
INSERT INTO objectUrl(disp_name, loggedIn) VALUES('please change this', true)
Is it possible to get the row number (column name userId) and if so how do you do it?
In MySQL it's called LAST_INSERT_ID(). I believe to be technically correct, the two statements should be wrapped in a transaction so that some other INSERT doesn't mess up what ID you get back.
In SQL Sever you have IDENT_CURRENT(‘tablename’) which will only grab it from that table (still need a transaction to be safe). You could also use SCOPE_IDENTITY() which theoretically will always return the one you expect as long as you aren't doing something weird with your connection.
For MySQL you have:
select last_insert_id()

How do I get the value of the autogenerated fields using Postgresql?

I have a postgres table like this:
CREATE SEQUENCE seq;
CREATE TABLE tbl (id INTEGER DEFAULT VALUE nextval('seq'), data VARCHAR);
When I insert into the table:
INSERT INTO tbl (data) VALUES ('something');
How can I get back the value of the id field for the record I just created?
(Note, I may have got some of the SQL syntax a bit off; the gist should be clear, though)
Suppose for the sake of argument that I'm not able to call currval on the same session because I don't control the transaction boundaries. I might be working in the same session with my next call, but I might not be, too.
You're looking for INSERT ... RETURNING. From The Manual's section on INSERT:
The optional RETURNING clause causes INSERT to compute and return value(s) based on each row actually inserted. This is primarily useful for obtaining values that were supplied by defaults, such as a serial sequence number. However, any expression using the table's columns is allowed. The syntax of the RETURNING list is identical to that of the output list of SELECT.
In the same session:
SELECT currval('seq');
EDIT: But if you can't use currval/nextval because you don't know if the inserting and selecting of the sequence value will occur in the same session, and if you're on postgresql 8.2 or later, you could probably write your insert statement like this.
INSERT INTO tbl (data) VALUES ('something') RETURNING id;
which should also return the last inserted id.
Use nextval and currval, take a look here: http://www.postgresql.org/docs/8.0/static/functions-sequence.html

SQL INSERT INTO returning autoincrement field

I'm a long time desktop app C++ programmer new to SQL. I need to insert into a table with an autoincrment field, and have that sql statement return the new value for the autoincrement field.
Something LIKE:
INSERT INTO Entrys ('Name','Description')
VALUES ('abc','xyz')
SELECT Entrys.EntryID WHERE EntryID=[THE ONE JUST INSERTED!]
Sorry for being a noob.
Assuming that you're using SQL Server, you can use scope_identity to return "the last identity value inserted into an identity column in the same scope. A scope is a module: a stored procedure, trigger, function, or batch. Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch."
INSERT INTO Entrys ('Name','Description') VALUES ('abc','xyz');
SELECT SCOPE_IDENTITY()
select scope_identity
insert into table values ('string value');select scope_identity()
Details here
In SQL Server, you can also use the OUTPUT clause on your INSERT statement:
INSERT INTO Entrys('Name', 'Description')
OUTPUT Inserted.EntryID
VALUES ('abc','xyz')
This will output the newly created IDENTITY field value.
In MySQL you can use LAST_INSERT_ID()
As #marc_s said for SQL Server, in PostgreSQL you can obtain the same behaviour with:
INSERT INTO Entrys ('Name','Description')
VALUES ('abc','xyz')
RETURNING EntryID;
RETURNING is also really useful when you're inserting several tuples and you want all the generated IDs for each of the rows.