473,748 Members | 10,649 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How can I get the Identity value of a newly inserted record?

Hi,

I insert a new record with a command:

private SqlCommand comInsert;

comInsert = conDataBase.Cre ateCommand();

comInsert.Comma ndType = CommandType.Tex t;

comInsert.Comma ndText = "Insert Into MyTable ( Col1, Col2) Values(1,2)";

comInsert.Execu teNonQuery();

Col3 is an Identity column which autoincrements. How can I get the value of
the inserted record

immediately after, in an multi-user environment, on a MS SQL DB?

Thanks,

Doru
Mar 27 '06 #1
8 1947
Check out the following article:

http://msdn.microsoft.com/library/de...anidcrisis.asp

Mar 27 '06 #2
Hello Doru,

Call SELECT @@idetity

DR> I insert a new record with a command:
DR>
DR> private SqlCommand comInsert;
DR>
DR> comInsert = conDataBase.Cre ateCommand();
DR>
DR> comInsert.Comma ndType = CommandType.Tex t;
DR>
DR> comInsert.Comma ndText = "Insert Into MyTable ( Col1, Col2)
DR> Values(1,2)";
DR>
DR> comInsert.Execu teNonQuery();
DR>
DR> Col3 is an Identity column which autoincrements. How can I get the
DR> value of the inserted record
DR>
DR> immediately after, in an multi-user environment, on a MS SQL DB?
DR>
DR> Thanks,
DR>
DR> Doru
DR>
---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche
Mar 27 '06 #3
Thanks Michael for the reply.
Would that return only my @@identity or it might return some other user's
value if that user got a new value inserted immediately after me?
"Michael Nemtsev" <ne*****@msn.co m> wrote in message
news:9c******** *************** ***@msnews.micr osoft.com...
Hello Doru,

Call SELECT @@idetity

DR> I insert a new record with a command:
DR> DR> private SqlCommand comInsert;
DR> DR> comInsert = conDataBase.Cre ateCommand();
DR> DR> comInsert.Comma ndType = CommandType.Tex t;
DR> DR> comInsert.Comma ndText = "Insert Into MyTable ( Col1, Col2)
DR> Values(1,2)";
DR> DR> comInsert.Execu teNonQuery();
DR> DR> Col3 is an Identity column which autoincrements. How can I get the
DR> value of the inserted record
DR> DR> immediately after, in an multi-user environment, on a MS SQL DB?
DR> DR> Thanks,
DR> DR> Doru
DR> ---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do
not cease to be insipid." (c) Friedrich Nietzsche

Mar 27 '06 #4
Hi,

Also note that you have to change from ExecuteNonQuery to ExecuteScalar

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"Michael Nemtsev" <ne*****@msn.co m> wrote in message
news:9c******** *************** ***@msnews.micr osoft.com...
Hello Doru,

Call SELECT @@idetity

DR> I insert a new record with a command:
DR> DR> private SqlCommand comInsert;
DR> DR> comInsert = conDataBase.Cre ateCommand();
DR> DR> comInsert.Comma ndType = CommandType.Tex t;
DR> DR> comInsert.Comma ndText = "Insert Into MyTable ( Col1, Col2)
DR> Values(1,2)";
DR> DR> comInsert.Execu teNonQuery();
DR> DR> Col3 is an Identity column which autoincrements. How can I get the
DR> value of the inserted record
DR> DR> immediately after, in an multi-user environment, on a MS SQL DB?
DR> DR> Thanks,
DR> DR> Doru
DR> ---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do
not cease to be insipid." (c) Friedrich Nietzsche

Mar 27 '06 #5
Hi,

It's better to use SCOPE_IDENTITY( )
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"Michael Nemtsev" <ne*****@msn.co m> wrote in message
news:9c******** *************** ***@msnews.micr osoft.com...
Hello Doru,

Call SELECT @@idetity

DR> I insert a new record with a command:
DR> DR> private SqlCommand comInsert;
DR> DR> comInsert = conDataBase.Cre ateCommand();
DR> DR> comInsert.Comma ndType = CommandType.Tex t;
DR> DR> comInsert.Comma ndText = "Insert Into MyTable ( Col1, Col2)
DR> Values(1,2)";
DR> DR> comInsert.Execu teNonQuery();
DR> DR> Col3 is an Identity column which autoincrements. How can I get the
DR> value of the inserted record
DR> DR> immediately after, in an multi-user environment, on a MS SQL DB?
DR> DR> Thanks,
DR> DR> Doru
DR> ---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do
not cease to be insipid." (c) Friedrich Nietzsche

Mar 27 '06 #6
Thanks Ignatio
"Ignacio Machin ( .NET/ C# MVP )" <ignacio.mach in AT dot.state.fl.us > wrote
in message news:e6******** ******@TK2MSFTN GP11.phx.gbl...
Hi,

It's better to use SCOPE_IDENTITY( )
--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"Michael Nemtsev" <ne*****@msn.co m> wrote in message
news:9c******** *************** ***@msnews.micr osoft.com...
Hello Doru,

Call SELECT @@idetity

DR> I insert a new record with a command:
DR> DR> private SqlCommand comInsert;
DR> DR> comInsert = conDataBase.Cre ateCommand();
DR> DR> comInsert.Comma ndType = CommandType.Tex t;
DR> DR> comInsert.Comma ndText = "Insert Into MyTable ( Col1, Col2)
DR> Values(1,2)";
DR> DR> comInsert.Execu teNonQuery();
DR> DR> Col3 is an Identity column which autoincrements. How can I get
the
DR> value of the inserted record
DR> DR> immediately after, in an multi-user environment, on a MS SQL DB?
DR> DR> Thanks,
DR> DR> Doru
DR> ---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do
not cease to be insipid." (c) Friedrich Nietzsche


Mar 27 '06 #7
Here is example of a proc I just did. It uses real exceptions instead of
returning exit codes.

ALTER PROCEDURE [dbo].[InsertMessage]
@LogName nvarchar(50),
@MsgID nvarchar(50),
@RefID nvarchar(50),
@Date datetime,
@From nvarchar(50),
@Subject nvarchar(100),
@Path nvarchar(200),
@Expires datetime,
@Body nvarchar(max)
AS
begin
set nocount on
declare @logid int
set @logid = -1

begin try
-- Get LogID from LogName.
select @logid = LogID
from Logs
where LogName = @LogName
if (@logid = -1)
raiserror ('LogName does not exist.', 16, 1);

-- Insert record
insert into [Messages]
([LogID]
,[Date]
,[MsgID]
,[RefID]
,[From]
,[Subject]
,[Path]
,[Expires]
,[Body])
values
(@logid
,@Date
,@MsgID
,@RefID
,@From
,@Subject
,@Path
,@Expires
,@Body)
if (@@rowcount < 1)
raiserror ('Insert failed.', -- Msg. Error_Number will be 50000.
16, -- Severity
1); -- State
declare @seq int
set @seq = Scope_Identity( )
select @seq
end try
begin catch
DECLARE @ErrorMessage NVARCHAR(4000);
DECLARE @ErrorSeverity INT;
DECLARE @ErrorState INT;

SELECT
@ErrorMessage = ERROR_MESSAGE() ,
@ErrorSeverity = ERROR_SEVERITY( ),
@ErrorState = ERROR_STATE();

-- Use RAISERROR inside the CATCH block to return error
-- information about the original error that caused
-- execution to jump to the CATCH block.
RAISERROR (@ErrorMessage, -- Message text.
@ErrorSeverity, -- Severity.
@ErrorState -- State.
);
end catch
end

And call it from client:
public static int AddMessage(stri ng logName, string msgID, string refID,
DateTime date, string from, string subject, string path, DateTime expires,
string body)

{

SqlCommand cmd;

using (SqlConnection conn = new SqlConnection(C onnectionString ))

{

cmd = new SqlCommand("Ins ertMessage", conn);

cmd.CommandType = CommandType.Sto redProcedure;

cmd.Parameters. Add("@LogName", SqlDbType.NVarC har, 50).Value =
logName;

cmd.Parameters. Add("@MsgID", SqlDbType.NVarC har, 50).Value = msgID;

cmd.Parameters. Add("@RefID", SqlDbType.NVarC har, 50).Value = refID;

cmd.Parameters. Add("@Date", SqlDbType.DateT ime).Value = date;

cmd.Parameters. Add("@From", SqlDbType.NVarC har, 50).Value = from;

cmd.Parameters. Add("@Subject", SqlDbType.NVarC har, 100).Value =
subject;

cmd.Parameters. Add("@Path", SqlDbType.NVarC har, 200).Value = path;

cmd.Parameters. Add("@Expires", SqlDbType.DateT ime).Value = expires;

cmd.Parameters. Add("@Body", SqlDbType.NVarC har).Value = body;

conn.Open();

int seq = (int)cmd.Execut eScalar();

return seq;

}

}
--
William Stacey [MVP]
Mar 27 '06 #8
On Mon, 27 Mar 2006 13:45:14 -0500, "Doru Roman" <do*******@roge rs.com> wrote:
Thanks Michael for the reply.
Would that return only my @@identity or it might return some other user's
value if that user got a new value inserted immediately after me?
"Michael Nemtsev" <ne*****@msn.co m> wrote in message
news:9c******* *************** ****@msnews.mic rosoft.com...
Hello Doru,

Call SELECT @@idetity

DR> I insert a new record with a command:
DR> DR> private SqlCommand comInsert;
DR> DR> comInsert = conDataBase.Cre ateCommand();
DR> DR> comInsert.Comma ndType = CommandType.Tex t;
DR> DR> comInsert.Comma ndText = "Insert Into MyTable ( Col1, Col2)
DR> Values(1,2)";
DR> DR> comInsert.Execu teNonQuery();
DR> DR> Col3 is an Identity column which autoincrements. How can I get the
DR> value of the inserted record
DR> DR> immediately after, in an multi-user environment, on a MS SQL DB?
DR> DR> Thanks,
DR> DR> Doru
DR> ---
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do
not cease to be insipid." (c) Friedrich Nietzsche

It certainly could return another users identity value, even from another table.

Use return scope_identity( ) instead:

search for scope_identity( ) in T-SQL Help
Otis Mukinfus
http://www.arltex.com
http://www.tomchilders.com
Mar 28 '06 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
74219
by: Who.Really.Really.Cares | last post by:
Hi! I guess this must be a FAQ but I'll give it a try. I've searched the web and usenet archive and found only negative answers. But most of them were dated like 3-4 years back. Hasn't anything changed since then? DB2 V7.2. The problem: I have a table with a primary key GENERATED BY DEFAULT AS IDENTITY. Then I INSERT several rows and force their PK's value. Then I see that my INSERTs haven't modified the value of DB2's internal IDENTITY
17
3591
by: Trevor Best | last post by:
I don't know if this has been reported before but it appears to be a bug with Access. If I create two tables both with an identity column then create an insert trigger on table1 that inserts a related record into table2, now create a form on table1 with a subform on table2. Insert records into the main form to your heart's content and everything's fine, each main record automatically gets a child record and so far the identity columns...
2
5459
by: WhiteEagl | last post by:
Hello, I would need some help with this identity column problem in SQLServer. I have a database with two tables. The Parent table has an Identity column. Parent (ParentID IDENTITY, Name) Child (ChildID, Name, ParentID)
9
20134
by: Micheal | last post by:
How do I get the @@identity value without using stored procedures in C#? I have the a table named 'sports' that has an @@identity value for the primary key. What I want to do is after I insert into into the 'sports' table, I want to get the @@identity value (primary key) for what I just inserted. I have to following code if this helps, thanks in advance:
3
1234
by: JIM.H. | last post by:
Hello, Let say myTable has two fields: ID and Name. ID is an identity field and increased sequentially by 1 each time a record is entered into table. dr=”MayName”; dataSet11.Tables.Rows.Add(dr); sqlDataAdapter1.Update(dataSet11, myTable);
3
6999
by: Jason L James | last post by:
Hi all, I recently wrote a vb.net app using oledb to an access database. When I inserted new rows in my datatable the identity column was automatically created. This app used an un-typed dataset. My current app is using sqlClient and a typed dataset that I created by exporting an xsd
1
1618
by: Craig | last post by:
In ASP.NET 2.0 and the formview control how do you get the value of the identity field of a newly inserted record? In ASP.NET 1.1 after the new record was saved you just said intNewIdentityID = Dataset.tblMtTable.IndentityID Simple but can't seem to do it in the formview. Thanks
15
3534
by: gunnar.sigurjonsson | last post by:
Im having some problem retrieving identity value from my newly inserted row into a view. I have two tables T1 and T2 which I define as following CREATE TABLE T1 ( id BIGINT GENERATED ALWAYS AS IDENTITY ( START WITH 1
2
1693
by: BobLewiston | last post by:
Most databases have multiple users. For these databases it is a good idea to auto-increment the identity column. I understand that the identity column is not incremented until the newly-created record is inserted. I guess this means the identity column is incremented when you actually reconnect to the database and insert the new record there, rather than just add the record to the locally-resident DataSet, correct? And I guess this also...
0
9541
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9370
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9247
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8242
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6074
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4602
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4874
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2782
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2215
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.