shani
shani

Reputation: 57

inserting values from one table into another table using sql/c#.net

I'm new to SQL and C# and am currently trying to create a library software. I'm facing a bit of a problem and would appreciate your input.

I have three tables:

BookId in the table Books and AuthorID in the table Author are indexed and are the primary keys.

What I need to do is,

My solution is to write two separate SQL statements to select the id columns and then enter it into the third table.

But what if there are two books with the same title?

Is there a way to get the last inserted values in SQL?

Upvotes: 1

Views: 2251

Answers (3)

marc_s
marc_s

Reputation: 754338

If those ID columns are of type INT IDENTITY and you're using SQL Server, then yes - you can get the last inserted value:

INSERT INTO dbo.Books(Title) VALUES('New Book')
DECLARE @NewBookID INT
SELECT @NewBookID = SCOPE_IDENTITY()

INSERT INTO dbo.Author(AuthorFname, AuthorLname) VALUES('John', 'Doe')
DECLARE @NewAuthorID INT
SELECT @NewAuthorID = SCOPE_IDENTITY()

INSERT INTO dbo.WrittenBy(BookID, AuthorID) VALUES(@NewBookID, @NewAuthorID)

The SCOPE_IDENTITY() function will return that last inserted IDENTITY value by the previous statement, which should be exactly what you're looking for, correct?

Upvotes: 1

anishMarokey
anishMarokey

Reputation: 11397

There are different ways are available :

 @@IDENTITY
      OR
 SCOPE_IDENTITY()
      OR
 IDENT_CURRENT(‘tablename’)

http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/

Upvotes: 1

Kon
Kon

Reputation: 27431

You should have a column called something like InsertedDate or CreatedDate. That's the best way to order by last inserted.

Other than that, this sounds like a homework question. This isn't want SO is for - search engines are your friends.

Upvotes: 0

Related Questions