Reputation: 57
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, Title
)AuthorID, AuthorFname, AuthorLname
)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,
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
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
Reputation: 11397
There are different ways are available :
@@IDENTITY
OR
SCOPE_IDENTITY()
OR
IDENT_CURRENT(‘tablename’)
Upvotes: 1
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