473,587 Members | 2,229 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Obtaining autonumber value after using recordset AddNew

I'm inserting a new record into an MS SQL database table
and I want to obtain the new records autonumber
immediately afterwards, as follows:
MadminRS.Cursor Location = adUseServer
MadminRS.Cursor Type = adOpenKeyset
MadminRS.LockTy pe = adLockOptimisti c
MadminRS.Open "NavBar", objConn, , , adCmdTable
MadminRS.AddNew
MadminRS("Url") = Request.Form("W ebsite")
MadminRS("Paren tRecNo") = 0
MadminRS("Menu" ) = "NavBar"
MadminRS("Seque nce") = 1000
MadminRS("Butto nName") = "Master Admin"
MadminRS("Link" ) = "Menu"
MadminRS("Cos") = "Admin"
MadminRS.Update
vRecNo = MadminRS("RecNo ") 'the autonumber field
The record is inserted in the table and the autonumber
field is created. vRecNo is blank, however. What is
wrong with this code? I have to obtain the record number
before closing the recordset because I may not be able to
locate the record subsequently.

Jul 19 '05 #1
9 19904
Don't use AddNew, use an INSERT statement.
http://www.aspfaq.com/2174
http://www.aspfaq.com/2191

--
Aaron Bertrand
SQL Server MVP
http://www.aspfaq.com/


"Roger Withnell" <an*******@disc ussions.microso ft.com> wrote in message
news:02******** *************** *****@phx.gbl.. .
I'm inserting a new record into an MS SQL database table
and I want to obtain the new records autonumber
immediately afterwards, as follows:
MadminRS.Cursor Location = adUseServer
MadminRS.Cursor Type = adOpenKeyset
MadminRS.LockTy pe = adLockOptimisti c
MadminRS.Open "NavBar", objConn, , , adCmdTable
MadminRS.AddNew
MadminRS("Url") = Request.Form("W ebsite")
MadminRS("Paren tRecNo") = 0
MadminRS("Menu" ) = "NavBar"
MadminRS("Seque nce") = 1000
MadminRS("Butto nName") = "Master Admin"
MadminRS("Link" ) = "Menu"
MadminRS("Cos") = "Admin"
MadminRS.Update
vRecNo = MadminRS("RecNo ") 'the autonumber field
The record is inserted in the table and the autonumber
field is created. vRecNo is blank, however. What is
wrong with this code? I have to obtain the record number
before closing the recordset because I may not be able to
locate the record subsequently.

Jul 19 '05 #2
Why are you using these expensive cursors? Keyset is 2x -> 3x more expensive
than other alternatives (eg a stored procedure, or even an inline SQL
statement).

Cheers
Ken
"Roger Withnell" <an*******@disc ussions.microso ft.com> wrote in message
news:02******** *************** *****@phx.gbl.. .
: I'm inserting a new record into an MS SQL database table
: and I want to obtain the new records autonumber
: immediately afterwards, as follows:
: MadminRS.Cursor Location = adUseServer
: MadminRS.Cursor Type = adOpenKeyset
: MadminRS.LockTy pe = adLockOptimisti c
: MadminRS.Open "NavBar", objConn, , , adCmdTable
: MadminRS.AddNew
: MadminRS("Url") = Request.Form("W ebsite")
: MadminRS("Paren tRecNo") = 0
: MadminRS("Menu" ) = "NavBar"
: MadminRS("Seque nce") = 1000
: MadminRS("Butto nName") = "Master Admin"
: MadminRS("Link" ) = "Menu"
: MadminRS("Cos") = "Admin"
: MadminRS.Update
: vRecNo = MadminRS("RecNo ") 'the autonumber field
: The record is inserted in the table and the autonumber
: field is created. vRecNo is blank, however. What is
: wrong with this code? I have to obtain the record number
: before closing the recordset because I may not be able to
: locate the record subsequently.
:
Jul 19 '05 #3
Hi

You can obtain the autonumber value by the SQL global variable @@IDENTITY. Just use recordet when inserting data and before closing the rescordset use something like

Set id = "select myid = @@IDENTITY from table_name", conn

you will get it in your code. Tell me if you need the full code.

Regards,
Bhaskardeep Khaund

Jul 19 '05 #4
>> Set id = "select myid = @@IDENTITY from table_name", conn

This is not valid syntax, and you don't select @@IDENTITY from a table, it
is a global variable. With SQL Server 2000, SCOPE_IDENTITY( ) is far safer
anyway, but it has to be issued on the *same* instance as the initial
query...

--
Aaron Bertrand
SQL Server MVP
http://www.aspfaq.com/


Jul 19 '05 #5
Hi,

The code is:-
<%
strSQL = "SET NOCOUNT ON INSERT INTO tblName(TextFie ld, NumberField)
VALUES('ABC', 123) SELECT @@IDENTITY AS NewID SET NOCOUNT OFF"

Set objConn = Server.CreateOb ject("ADODB.Con nection")
objConn.Open strConnection
Set objRS = objConn.Execute (strSQL)
varNewID = objRS("NewID")
objConn.Close()
Set objConn = Nothing
Set objRS = Nothing
%>

And the SCOPE _IDENTITY returns the last column entered in the field irrespective of the session, if another column is inserted into the database between the column you have inserted and sending the autonumber column value, the value retrieved would be wrong.
Regards,
Bhaskardeep Khaund
Jul 19 '05 #6
>> And the SCOPE _IDENTITY returns the last column entered in the field
irrespective of the session,

Not true, I suggest you read up in Books Online, about the differences
between @@IDENTITY, SCOPE_IDENTITY, and IDENT_CURRENT() . I think you have a
couple of these mixed up.

--
Aaron Bertrand
SQL Server MVP
http://www.aspfaq.com/
Jul 19 '05 #7
After inserting the record, I'm using "ident_curr ent
('table')" to establish the autonumber of the record.
Does it guarantee that the result will be the number of
the record I have just inserted or could it be the number
of a record inserted meanwhile? If the latter, does
using "scope_identity ()" guarantee that it is the number
of my record? If so, how do I issue it on the "same"
instance as the initial query?
-----Original Message-----
And the SCOPE _IDENTITY returns the last column
entered in the fieldirrespective of the session,

Not true, I suggest you read up in Books Online, about the differencesbetween @@IDENTITY, SCOPE_IDENTITY, and IDENT_CURRENT (). I think you have acouple of these mixed up.

--
Aaron Bertrand
SQL Server MVP
http://www.aspfaq.com/
.

Jul 19 '05 #8
Roger Withnell wrote:
After inserting the record, I'm using "ident_curr ent
('table')" to establish the autonumber of the record.
Does it guarantee that the result will be the number of
the record I have just inserted
No. From BOL:
Returns the last identity value generated for a specified table in any
session and any scope.

So you may wind up getting the ID of a row inserted by some other process.
or could it be the number
of a record inserted meanwhile? If the latter, does
using "scope_identity ()" guarantee that it is the number
of my record?
Yes. Again from BOL:
[SCOPE_IDENTITY] ... Returns 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. Thus, two statements are in the same
scope if they are in the same stored procedure, function, or batch.

I think this is pretty clear ...

If so, how do I issue it on the "same"
instance as the initial query?


As always, I suggest using a stored procedure:

Using Query Analyzer, run this script (adapt it to your table of course):
CREATE PROCEDURE InsRow (
@TextCol varchar(50),
@IntCol int) AS
SET NOCOUNT ON
INSERT INTO tblName(TextCol , IntCol)
VALUES(@TextCol ,@IntCol)
SELECT SCOPE_IDENTITY As [NewID]

Then in ASP:

dim rs, cn
Set cn= Server.CreateOb ject("ADODB.Con nection")
cn.Open strConnection
Set rs = Server.CreateOb ject("ADODB.Rec ordset")
cn.InsRow "ABC",123,r s

Of course, this is inefficient, since it is using a heavy recordset object
to return a single value to the client. My preference is to use an output
parameter, retrieving its value using a Command object in ASP:

CREATE PROCEDURE InsRow (
@TextCol varchar(50),
@IntCol int,
@NewID int output) AS
SET NOCOUNT ON
INSERT INTO tblName(TextCol , IntCol)
VALUES(@TextCol ,@IntCol)
SET @NewID = SCOPE_IDENTITY

dim cn,cmd,newID, params
Set cn= Server.CreateOb ject("ADODB.Con nection")
cn.Open strConnection
Set cmd= Server.CreateOb ject("ADODB.Com mand")
With cmd
.CommandText = "InsRow"
.CommandType = adCmdStoredProc
Set .ActiveConnecti on = cn
Set params = .Parameters
params.Append .CreateParamete r("RETURN_VALUE ", adInteger, _
adParamReturnVa lue)
params.Append .CreateParamete r("@TextCol", adVarChar, _
adParamInput,50 ,"ABC")
params.Append .CreateParamete r("@IntCol", adInteger, _
adParamInput,,1 23)
params.Append .CreateParamete r("@NewID", adInteger, _
adParamOutput)
.Execute ,,adExecuteNoRe cords
End With
newID = params(3).value

Admittedly, it's more code, and it can be tricky to write, but it is more
efficient than using a recordset. The trickiness can be alleviated by using
a code generator, such as the one I wrote which is available here:
http://www.thrasherwebdesign.com/ind...asp&c=&a=clear
But, if you have some sort of phobia about using stored procedures, you can
send a string of batched commands to SQL Server so they all get executed in
the same scope. You can use what Bhaskardeep posted:

strSQL = "SET NOCOUNT ON INSERT INTO tblName(TextFie ld, NumberField)
VALUES('ABC', 123) SELECT @@IDENTITY AS NewID SET NOCOUNT OFF"

Just substitute "SCOPE_IDENTITY " for "@@IDENTITY "

HTH,
Bob Barrows
--
Microsoft MVP - ASP/ASP.NET
Please reply to the newsgroup. This email account is my spam trap so I
don't check it very often. If you must reply off-line, then remove the
"NO SPAM"
Jul 19 '05 #9
> After inserting the record, I'm using "ident_curr ent
('table')" to establish the autonumber of the record.
Does it guarantee that the result will be the number of
the record I have just inserted or could it be the number
of a record inserted meanwhile?
IDENT_CURRENT returns the most recent IDENTITY value generated for that
table. That might have been yours, or it might have been someone else's.

SCOPE_IDENTITY( ) returns the most recent IDENTITY value generated by *you*.
Unlike @@IDENTITY, this does not include the IDENTITY value generated by a
trigger on the table that generated the IDENTITY value you are interested
in.

SCOPE_IDENTITY( ) is safest, @@IDENTITY should be used if you need to support
SQL Server 7.0, and IDENT_CURRENT() should only be used if you're curious
what the *current* value is (and don't want to use SELECT
MAX(identityCol umn), not if you're interested in finding out what you just
did.
of my record? If so, how do I issue it on the "same"
instance as the initial query?


sql = "SET NOCOUNT ON; " & _
"INSERT table(col) VALUES(vals);" & _
"SELECT SCOPE_IDENTITY( )"
set rs = conn.execute(sq l)
response.write rs(0)

--
Aaron Bertrand
SQL Server MVP
http://www.aspfaq.com/
Jul 19 '05 #10

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

Similar topics

2
2825
by: Jan Hendrickx | last post by:
Hi all, I use (something like) following code to add new records to a database, but it doesn't work!!! I need to know the value of an AutoNumber-field when I add the record. Why doesn't it work and how can I make it work??? I think it should be easy, but I can't figure it out!
1
15924
by: Steve Leferve | last post by:
Hey folks - I have some VBA code for creating a row and related sub-rows from a 'wizard' form. I'm using sql 'INSERT' statements to create the rows. My problem is that I need to get the autonumber id field from the parent table to properly insert the rows in the subtable. PHP has a function for MySQL called mysql_last_id(). Is there...
2
2258
by: Danny | last post by:
I was trying to tihnk of solutions to the table in access being out of order when i use: DoCmd.TransferSpreadsheet in code to import an excel file. 1. I could read the excel file from access. Does anyody have access code to open an exel sheet and read it into a table in access in code? 2. have the user maintain an autonumber like...
1
1584
by: Will | last post by:
Hi, I have a form which calculates a final cost (frmWorkCosts, data stored in tblWorkCosts) and once calculated adds this final cost (Which isn't saved in tblWorkCosts) into a different table (tblLabour) as a new record. Once it has done this I want it to save the Labour ID (Key Field/Autonumber in tblLabour) to the Labour ID field in the...
22
7644
by: Dariusz Kuliński / TaKeDa | last post by:
I guess that was asked milion times, but I don't have good luck finding working answer on google. Most of the answers tell what to do, but not how. My situation is that I want to have ID in following format: <letter>-<three digits> i.e. A-001
1
602
by: jimfortune | last post by:
Sometimes I use Autonumber fields for ID fields. Furthermore, sometimes I use those same fields in orderdetail type tables. So it's important in that case that once an autonumber key value is assigned to a record that it doesn't change. Occasionally I find that due to corruption or an accidental deletion and restore of a record from a...
4
3325
by: dhcomcast | last post by:
We're starting to use Oracle for the back-end instead of a separate Access .mdb file for the data and everything as gone surprisingly well so far. We are learning Oracle as we go; Yikes! But we have very patient DBA's at the main office to answer newbie questions. Using Access 2002 with linked ODBC tables to Oracle 9 (9i? not sure), ODBC...
21
1883
by: MLH | last post by:
I have an A97 database table (tblCorrespondence] in a database installed at 2 sites. The table's key field is not a natural key - its an autonumber field. Here are the values at the 2 sites. First, site #1. Then, site #2. If you plot them, you'll see why I'm worried - I'm afraid I'll be running out-a-numbers soon. For the life of me, I...
3
2195
by: troy_lee | last post by:
I have the following code. Set rstDB = CurrentDb Set rstEvalForm = CurrentDb.OpenRecordset("tblRMAEval", dbOpenDynaset) With rstEvalForm 'Add a new record to the end of the Recordset Object. .AddNew ! = Me. ! = Me.cboEvalDate ! = Me.cboTechName
0
7843
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8339
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...
1
7967
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
1
5712
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5392
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...
0
3840
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...
0
3872
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2347
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1185
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...

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.