views:

52

answers:

5

I'm just getting my head around insert statements today after getting sick of cheating with Dreamweaver's methods to do this for so long now (please don't laugh).

One thing I'm trying to figure out is how to get the ID value of a newly inserted record so I can redirect the user to that page if successful.

I have seen some examples which talk about stored procedures, but they're double dutch for me at the moment and I'm yet to learn about these, let alone how to use these from within my web pages.

Summary

How do I, using my code below retrieve the record ID for what the user has just inserted.

Workflow

Using a HTML form presented on an ASP page (add.asp), a user will submit new information which is inserted into a table of a database (treebay_transaction).

On pressing submit, the form data is passed to another page (add_sql.asp) which takes the submitted data along with additional information, and inserts it into the required table.

If the insert is successful, the id value of the new record (stored in the column treebay_transaction_id) needs to be extracted to use as part of a querystring before the user is redirected to a page showing the newly inserted record (view.asp?id=value).

Sample code - add_sql.asp

<!--#include virtual="/Connections/IntranetDB.asp" -->
...
<html>
<body>
<%
set conn = Server.CreateObject("ADODB.Connection")
conn.ConnectionString = MM_IntranetDB_STRING
conn.Open ConnectionString
...
sql="INSERT INTO treebay_transaction (treebay_transaction_seller,treebay_transaction_start_date,treebay_transaction_expiry_date,treebay_transaction_title,treebay_transaction_transaction_type,treebay_transaction_category,treebay_transaction_description,treebay_transaction_status)"
sql=sql & " VALUES "
sql=sql & "('" & CurrentUser & "',"
sql=sql & "'" & timestampCurrent & "',"
sql=sql & "'" & timestampExpiry & "',"
sql=sql & "'" & Request.Form("treebay_transaction_title") & "',"
sql=sql & "'" & Request.Form("treebay_transaction_transaction_type") & "',"
sql=sql & "'" & Request.Form("treebay_transaction_category") & "',"
sql=sql & "'" & Request.Form("xhtml1") & "',"
sql=sql & "'3')"

on error resume next
conn.Execute sql,recaffected
if err<>0 then
%>
<h1>Error!</h1>
<p>
...error text and diagnostics here...
</p>
<%
else
    ' this is where I should be figuring out what the new record ID is
    recordID = ??
    ' the X below represents where that value should be going
    Response.Redirect("index.asp?view.asp?id='" & recordID & "'")
end if
conn.close
%>
</body>
</html>
+1  A: 

Run this after your execute statement and before you close your connection:

lsSQL = "SELECT @@IDENTITY AS NewID"
Set loRs = loConn.Execute(lsSQL)
llID = loRs.Fields("NewID").value

I pulled it from here: http://www.kamath.com/tutorials/tut007_identity.asp

spinon
@Spinon: Thanks for that lead. Using an MS SQL 2005 server, and I can make my resulting SQL string work without a problem via SQL Server Manager. Whenever I try it via the ASP page in question (add_sql.asp) it returns a 424 - object required error. I've placed a sample of the page in its latest form at http://bit.ly/d3Cr1I. If you could take a look and figure out where I've messed up it would be appreciated.
thewinchester
Do you need to use NextRecordSet since you are only returning one recordset? I don't remember as it has been a long time since I have used this. p.s. Also you really should take note of what people are saying in here about sanitizing your data before using directly in query. You are leaving yourself wide open for problems.
spinon
+1  A: 

look to @@IDENTITY, SCOPE_IDENTITY or IDENT_CURRENT

This makes the assumption that your ID field is an IDENTITY INSERT field. Also consider ramifications of the various options listed, as each one acts and performs slightly differently.

http://sqlserverpedia.com/wiki/Functions_-_@@IDENTITY,_SCOPE_IDENTITY,_IDENT_CURRENT

Stephen Wrighton
+2  A: 

It depends on the database you are using, in SQL Server you can get the @@IDENTITY or SCOPE_IDENTITY() see: http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/

But one thing I want to warn you, the code above has SEVERE security vulnerabilities, namely SQL Injection attack, please stay away from concatenating strings that are coming from users, you should use command paramaters.

CarlosAg
+1  A: 

Build your sql variable as you have been. Let's make one trip to the DB instead of two. We'll use SCOPE_IDENTITY() right in the same statement(s) as the INSERT to avoid many trips to the database.

Add this when building your SQL statement:

sql=sql & "; SELECT SCOPE_IDENTITY() As NewTreebayTransactionID"

'now execute the insert and receive the ID in one Execute statement.
 set newTransactionResults = conn.Execute(sql)

 'here is our new ID.
 recordID = newTransactionResults("NewTreebayTransactionID")

As soon as that's done:

  • sanitize your data inputs from your user
  • use parameterized statements
p.campbell
thewinchester
@thewinchster: indeed, perhaps remove the RecordsAffected parameter for now?
p.campbell
@p.campbell: Yes, that helped somewhat but kept throwing up object exceptions. Finally added 'Set newRS = newRS.NextRecordSet()' after reading the link provided by spinon, and now working perfectly.
thewinchester
+1  A: 
Set objConn = CreateObject("ADODB.Connection")
set rs = Server.CreateObject("ADODB.Recordset")
        objConn.Open "DSN=connectionName"
        rs.CursorLocation = 3
        rs.Open "treebay_transaction", objConn, 3, 3

        rs.AddNew fieldlist,values 'see link bellow to see how to fill this
        rs.Update
        bookmark = rs.absolutePosition  ' First, store the location of you cursor
        rs.Requery                      ' Next, update your recordset with the data from the database
        rs.absolutePosition = bookmark  ' Finally, change your cursor back
        recordID = rs("ID")

rs.AddNew documentation: http://www.w3schools.com/ado/met_rs_addnew.asp

Noam Smadja