Inserting Data Into Two Tables in ASP.NET

One of the most common questions on the net these days is how to do the following scenario:
“How do I insert data into one table, get the ID from that table and insert that ID and other data, into the second table?”

This tutorial uses the SQL Server managed provider for demonstration purposes. The most widely accepted ‘best’ way to accomplish this, would be to create a Stored Procedure in SQL Server to do it all for you, so that’s the direction this tutorial will take….
Here’s one I just snipped out of one of mine and edited a little:

CREATE   PROCEDURE procInsSamples
@CategoryID int,
@Title varchar(100),
@Description text,
@Link varchar(150),
@Whatever
AS
Begin
	Set NoCount on
	DECLARE @WhateverID INT
	Insert Table1(Title,Description,Link,Whatever)
	Values
	(@title,@description,@link,@Whatever)

	Select @WhateverID=@@Identity

	Insert into Table2
	(CategoryID,WhateverID)
	Values
	(@CategoryID,@WhateverID)
End

This way, you take input from a form (wherever) and insert it into table one – then the next line gets the ID from the newly entered data:

Continues…

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>