Forum Moderators: open
Let's say I insert a new entry in a table with a query such as:
INSERT INTO tblUsers ( userName ) VALUES ('" & strUserName & "')
The table has a field userId which is an autonumber. My question is, is there a way to retrieve the userId generated by the INSERT, so I can then use this userId right away for other purposes in the following lines of code?
Btw, i'm using ASP/VBscript with an Access DB.
Thanks for any assistance.
If you were using SQL, you could pull the IDENTITY like so:
SQL = "INSERT INTO tblTemp (name) VALUES('" & yourname & "'); SELECT idNew = @@IDENTITY FROM tblTemp"
set rs = conn.execute(SQL)
set rsNew = rs.nextrecordset
intNewID = rsNew("idNew")
-Matt
With mySQL I use:
SQL = "SELECT LAST_INSERT_ID() as idNew FROM tblTemp;"
set rs = conn.execute(SQL)
intNewID = rs("idNew")
This should be performed directly after your INSERT statement. I can't remember the full wording, but with this you can't get a wrong ID. It has something to do with mySQL assigning you some type of session to keep the data going where it's supposed to go. I should probably look it up again. I haven't used mySQL in a few months.
-Matt
create procedure cspInsertStuff
@i_vValue as varchar(10)
@o_iID AS int output
as
insert into tblUsers(username)
values(@i_vValue)
set @o_iID = @@IDENTITY
go
then call it from a command
set oCmd = server.createobject("adodb.command")
With oCmd
.CommandType = adCmdStoredProc
.CommandText = "cspInsertStuff"
.Parameters.Append .CreateParameter("@i_vValue", advarchar, adparaminput, 10, "your value")
.Parameters.Append .CreateParameter("@o_iID", adInteger, adParamOutput, , returnSprocOutput)
.ActiveConnection = yourConnObjHere
.Execute
returnSprocOutput = .Parameters("@o_iID").Value
End With
Set oCmd = Nothing
I find it strange that there's no fool-proof (and easy) way to do this (in Access), since this is something that can be needed quite often.
no fool-proof (and easy) way to do this (in Access)
Unfortunately, there is nothing easy or fool-proof about Access.
It's a good little database for desktop applications, but it's not very standard and there are way too many quirks to work around.
But it beats the alternatives - FileMaker Pro? Panorama? Microsoft Works? Etch-a-sketch?
set objConn = Server.CreateObject("ADODB.Connection")
objConn.Open sDSN
objConn.Execute(sSQL)
Set objrs = objConn.Execute("select @@Identity")
response.write objrs(0)
objRS.close
Set objRS = nothing
objConn.close
set objConn = nothing