开发者

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:

  • 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 n开发者_C百科eed 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?


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?


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/


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜