1

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:

  • Books (BookID, Title)
  • Author (AuthorID, AuthorFname, AuthorLname)
  • WrittenBy (BookID, AuthorID)

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

What I need to do is,

  • get the bookId from the books table,
  • get the authorID from the author table,
  • insert these two values into the writtenby table

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?

3
  • possible duplicate stackoverflow.com/questions/5048602/… Commented May 5, 2011 at 10:48
  • How will you determine that which bookid should link with which authorid? Commented May 5, 2011 at 10:50
  • the user will be entering these details into a form. so the data taken from it will let me know which bookid will belong to which authorid. But when retrieving the data, the table writtenby will let me know which author wrote which book Commented May 5, 2011 at 11:14

3 Answers 3

1

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?

Sign up to request clarification or add additional context in comments.

Comments

1

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/

1 Comment

Thank you. the link was more than helpful!. this is what i was looking for.
0

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.

1 Comment

I assure you, this is an actual problem i encountered and an actual question i wrote.It's not a homework question. I am learning sql and c# as I go with this project.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.