How can I get the last inserted primary key? - sql

I'm using SQL Server 2005 with a table with a primary key field with the type varchar(40). I have to get the last inserted record's primary key value. I have tried scope_identity but it is not working. How can I get this?

I found the result.
Code:
insert into T
output inserted.pk
values ('new item');

If your ID is a varchar I suppose it's not auto generated so you should know it before you insert a record . BTW can't you just select your id after you insert a record?
Something like this:
CREATE PROC InsertXXX( ... value parameters...)
AS
BEGIN
INSERT .....
SELECT ID FROM MyTable
END
UPDATED :
If you want to know the last inserted record and its ID before inserting a new record it can be a little bit harder depending on ID values.
If you can find the last record by sorting ID column you can do it as follows:
SELECT Max(ID) FROM myTable
If not you can have a DateTime filed (CreationDate for example) that holds the time of insertion of the record.Then you can do as follows:
SELECT ID FROM MyTable WHERE CreationDate=(SELECT Max(CreationDate) FROM MyTable)

Related

Get last generated id asp.net

So I have 2 Tables in one Database (Table1 and Table2). What I want to do is to get the last generated ID (which is primary key) from the first table (Table1) and add it to another table (Table2).
For example. The Last generated ID from Table1, column NRRENDOR is 25 (I have deleted the rows that's why it shows 22, it is primary key). If I add a row to Table1 it will generate number 26 on column NRRENDOR (First picture). But when number 26 is added to column NRRENDOR from Table 1, I want it to be added to Table2, column NRD too (Second Picture).
You should use a sql-query like the one below after inserting the new element to the first table.
Insert into table2 (id) values(Select top 1 ID from table1 order by id desc)
This should work in sql-server 2008 and newer.
From MySQL Reference Manual, 20.6.14.3 How to Get the Unique ID for the Last Inserted Row
INSERT INTO NRRENDOR (auto, field) VALUES(NULL, 'value');
generate ID by inserting NULL
INSERT INTO NRD (id, field) VALUES(LAST_INSERT_ID(), 'value');
use ID in second table.
Or you can get the last insert id manually executing the following query immediately after the INSERT into NRRENDOR
SELECT last_insert_id()
and use it later in your second INSERT query for NRD.

SQL insert row with one change

I have this table:
Table1:
id text
1 lala
And i want take first row and copy it, but the id 1 change to 2.
Can you help me with this problem?
A SQL table has no concept of "first" row. You can however select a row based on its characteristics. So, the following would work:
insert into Table1(id, text)
select 2, text
from Table1
where id = 1;
As another note, when creating the table, you can have the id column be auto-incremented. The syntax varies from database to database. If id were auto-incremented, then you could just do:
insert into Table1(text)
select text
from Table1
where id = 1;
And you would be confident that the new row would have a unique id.
Kate - Gordon's answer is technically correct. However, I would like to know more about why you want to do this.
If you're intent is to have the field increment with the insertion of each new row, manually setting the id column value isn't a great idea - it becomes very easy for there to be a conflict with two rows attempting to use the same id at the same time.
I would recommend using an IDENTITY field for this (MS SQL Server -- use an AUTO_INCREMENT field in MySQL). You could then do the insert as follows:
INSERT INTO Table1 (text)
SELECT text
FROM Table1
WHERE id = 1
SQL Server would automatically assign a new, unique value to the id field.

How to return the last primary key inserted

I ask about alternative or similar query in informix to perform the following:
INSERT INTO days (depcode,studycode,batchnum) values (1,2,3);SELECT SCOPE_IDENTITY();
I want a query to return the SCOPE_IDENTITY() during insertion statement
I know that in t-sql you have the OUTPUT statement?
Where [KEY] is the column name of your primary key and #OUT_KEY is a variable you need to declare
INSERT INTO days
(
depcode,
studycode,
batchnum
)
OUTPUT INSERTED.[KEY] INTO #OUT_KEY
VALUES
(
1,2,3
)
EDIT
For informix you can use
SELECT DBINFO( 'sqlca.sqlerrd1' )
FROM systables
WHERE tabid = 1;
Presuming your pk column is SERIAL
I use this sql statement Select ##Identity after I inserted rows. It gives me the ID of the last inserted row. I´m using an accessdatabase. I don´t know if it work with your database.

Retrieve inserted row ID in SQL

How do I retrieve the ID of an inserted row in SQL?
Users Table:
Column | Type
--------|--------------------------------
ID | * Auto-incrementing primary key
Name |
Age |
Query Sample:
insert into users (Name, Age) values ('charuka',12)
In MySQL:
SELECT LAST_INSERT_ID();
In SQL Server:
SELECT SCOPE_IDENTITY();
In Oracle:
SELECT SEQNAME.CURRVAL FROM DUAL;
In PostgreSQL:
SELECT lastval();
(edited: lastval is any, currval requires a named sequence)
Note: lastval() returns the latest sequence value assigned by your session, independently of what is happening in other sessions.
In SQL Server, you can do (in addition to the other solutions already present):
INSERT INTO dbo.Users(Name, Age)
OUTPUT INSERTED.ID AS 'New User ID'
VALUES('charuka', 12)
The OUTPUT clause is very handy when doing inserts, updates, deletes, and you can return any of the columns - not just the auto-incremented ID column.
Read more about the OUTPUT clause in the SQL Server Books Online.
In Oracle and PostgreSQL you can do this:
INSERT INTO some_table (name, age)
VALUES
('charuka', 12)
RETURNING ID
When doing this through JDBC you can also do that in a cross-DBMS manner (without the need for RETURNING) by calling getGeneratedKeys() after running the INSERT
I had the same need and found this answer ..
This creates a record in the company table (comp), it the grabs the auto ID created on the company table and drops that into a Staff table (staff) so the 2 tables can be linked, MANY staff to ONE company. It works on my SQL 2008 DB, should work on SQL 2005 and above.
===========================
CREATE PROCEDURE [dbo].[InsertNewCompanyAndStaffDetails]
#comp_name varchar(55) = 'Big Company',
#comp_regno nchar(8) = '12345678',
#comp_email nvarchar(50) = 'no1#home.com',
#recID INT OUTPUT
-- The '#recID' is used to hold the Company auto generated ID number that we are about to grab
AS
Begin
SET NOCOUNT ON
DECLARE #tableVar TABLE (tempID INT)
-- The line above is used to create a tempory table to hold the auto generated ID number for later use. It has only one field 'tempID' and its type INT is the same as the '#recID'.
INSERT INTO comp(comp_name, comp_regno, comp_email)
OUTPUT inserted.comp_id INTO #tableVar
-- The 'OUTPUT inserted.' line above is used to grab data out of any field in the record it is creating right now. This data we want is the ID autonumber. So make sure it says the correct field name for your table, mine is 'comp_id'. This is then dropped into the tempory table we created earlier.
VALUES (#comp_name, #comp_regno, #comp_email)
SET #recID = (SELECT tempID FROM #tableVar)
-- The line above is used to search the tempory table we created earlier where the ID we need is saved. Since there is only one record in this tempory table, and only one field, it will only select the ID number you need and drop it into '#recID'. '#recID' now has the ID number you want and you can use it how you want like i have used it below.
INSERT INTO staff(Staff_comp_id)
VALUES (#recID)
End
-- So there you go. I was looking for something like this for ages, with this detailed break down, I hope this helps.

Query regarding SQL Insert in SQL Server?

I am using SQL Server 2008 and developing a project which is in maintenance phase.
I want to insert record in a table whose primary key is an Integer but not an identity. e.g. table name is tblFiles and fields are ID, FileName, FileContent.
Actually that table is in use so I don’t want to make any schema change in it. And I want the key after row insertion because I have to put that in another table. Existing values in the Id column are different integer, means not in sequence.
So I want the query that also returns me the Id value. So I want to insert only FileName and FileContent and some sort of sql to whom I can embed in my insert query which insert a unique Id and also send me that id
Well, if it's not an IDENTITY field - don't you already have to specify the "ID" in your insert for it to succeed ? If so - you already have the ID! Or what am I missing? Is the ID determined by a trigger or something??
If so, try this query:
INSERT INTO dbo.tblFiles(FileName, FileContent)
OUTPUT inserted.ID
VALUES ('yourfile.name', 'your contents')
This should return the newly inserted ID from the INSERT query.
Marc
Change the Columns Identity Specification > Is Identity to Yes.
The after inserting into the table you can
Select SCOPE_IDENTITY()
to get the integer that was just added and return this in your SP.
If you really can't edit the database schema maybe you could add another table to the database that has two columns called ID and CurrentDate. Make the ID column an Identity. In your code insert into this table first select SCOPE_IDENTITY() and then use the integer returned to insert as the ID in your tblFles table.
P.S. Stop prefixing your table with tbl that's so 1999. :)
You could create a unique integer, not so elegantly, using
SELECT MAX(ID) + 1 FROM tblFiles
And simply return this from your query or sproc as the case maybe. Otherwise follow as marc_s says if it is known already.
UPDATE: have to say, rather than this fudge as requested, I would strongly recommend pushing back hard and getting table changed so this is an identity column, as this is what is. all answers so far are simply fudges, mine especially.
so my final query look like...
Insert into dbo.tblData (Id, FName, LName)
output inserted.Id
values ((SELECT MAX(ID) + 1 FROM dbo.tblData), 'xyz', 'abc')
We can assign max(ID)+1 in to an integer variable, then we can Insert
Declare #ID int
Select #ID = ISNULL(MAX(ID),0) + 1 FROM tblFiles
INSERT INTO tblFiles
(
ID, FileName, FileContent
)
Select #ID,'FileName','FileContent'
This insertion is direct,
INSERT INTO tblFiles
(
ID, FileName, FileContent
)
Select (Select ISNULL(MAX(ID),0) + 1 FROM tblFiles),'FileName','FileContent'
Here we have to use ISNULL condition because there is no data in table then it will return Null. So ISNULL(MAX(ID),0) + 1 this condition will give Data is null then 0+1=1.
Thank you