Results 1 to 2 of 2

Thread: Getting rowId of recently inserted row

  1. #1

    Thread Starter
    Addicted Member silentthread's Avatar
    Join Date
    Jun 2006
    Location
    Miami, Florida
    Posts
    143

    Getting rowId of recently inserted row

    Hi,

    I have 2 SQL tables, and a user web form (aspx.net page) that when it gets filled out, it makes inserts into those 2 tables.

    Example of table design...

    Table 1
    RowId, Name, LastName

    Table 2
    RowId, Comments


    The problem is that after I make the first insert into Table1, I need to somehow get the row id of that row and use it in my second insert so I can link them.

    Is there a way to do this in SQL?
    Watch media as you download it! Excellent tool!
    FREE CUBA!
    MyBlog
    If you feel my post has helped, please rate it.

  2. #2
    Frenzied Member
    Join Date
    May 2006
    Location
    Toronto, ON
    Posts
    1,093

    Re: Getting rowId of recently inserted row

    Create a stored procedure and pass in the parameters you need for both tables. Then insert into the first table, grab the identity value and use it to insert into the second table.

    For instance:

    Code:
    CREATE PROCEDURE dbo.spUpdateStuff
    (
    @FirstName varchar(50),
    @LastName varchar(50),
    @Comments varchar(100)
    )
    AS
    
    DECLARE @rowID int
    
    INSERT Table1 (FirstName, LastName)
    	VALUES (@FirstName, @LastName)
    
    SELECT @rowID = @@IDENTITY
    
    INSERT Table2 (RowID, Comments)
    	VALUES (@rowID, @Comments)
    
    GO
    (VB/C#) is clearly superior to (C#/VB) because it (has/doesn't have) <insert trivial difference here>.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width