| 
 
	
		| View previous topic :: View next topic |  
		| Author | Message |  
		| Scott 
 
 
 Joined: 14 Oct 2004
 Posts: 11
 
 
 | 
			
				|  Posted: Thu Oct 14, 2004 3:23 pm    Post subject: Get the unique ID of a newly inserted row in MS SQL |   |  
				| 
 |  
				| I have a stored procedure in MS SQL, which simply inserts a new record in one of my tables. I want to get the unique ID of the newly inserted row. How can I do that? 
 I don’t have much db experience, so any help is appreciated.
 
 
 Thanks,
 
 Scott
 |  |  
		| Back to top |  |  
		|  |  
		| SMatanza 
 
 
 Joined: 14 Oct 2004
 Posts: 1
 
 
 | 
			
				|  Posted: Thu Oct 14, 2004 10:45 pm    Post subject: Try this ... |   |  
				| 
 |  
				| Hey... Try this:
 
 <%
 Set connInsert = Server.CreateObject("ADODB.Connection")
 'Replace with your own connection string.
 connInsert.Open "Driver={SQL Server};Server=(local);Database=YourDatabase;UID=workuser;PWD=workuser;"
 varInsertCommand = "INSERT INTO tableName(TextField, NumericField) VALUES ('ABCDE', 12345);"
 'Execute the insert command
 connInsert.Execute(varInsertCommand)
 'Create a recordset and SELECT the new Identity
 Set rsNewID = connInsert.Execute("SELECT @@IDENTITY")
 'Store the value of the new identity in variable varNewID
 NewID = rsNewID(0)
 rsNewID.Close
 Set rsNewID = Nothing
 %>
 
 Good Luck !
 |  |  
		| Back to top |  |  
		|  |  
		| Scott 
 
 
 Joined: 14 Oct 2004
 Posts: 11
 
 
 | 
			
				|  Posted: Fri Oct 15, 2004 6:58 am    Post subject: |   |  
				| 
 |  
				| Thank you very much! 
 
 Regards,
 
 Scott
 |  |  
		| Back to top |  |  
		|  |  
		| raven 
 
 
 Joined: 31 Jan 2006
 Posts: 41
 
 
 | 
			
				|  Posted: Wed Feb 01, 2006 2:13 am    Post subject: |   |  
				| 
 |  
				| This example given can actually be problematic on a very busy system. What you may want to consider is wrapping the calls in a transaction in order to be certain the identity you are returning is the identity in the scope of your current transaction. 
 Additionally you can avoid multiple calls by turning this into a single stored procedure returning the @@IDENTITY
 _________________
 Programmers do it in code
 |  |  
		| Back to top |  |  
		|  |  
		|  |  
  
	| 
 
 | You cannot post new topics in this forum You cannot reply to topics in this forum
 You cannot edit your posts in this forum
 You cannot delete your posts in this forum
 You cannot vote in polls in this forum
 
 |  
 Powered by phpBB © 2001, 2002 phpBB Group
 
 |