dimanche 1 mars 2015

Insert into two tables in one statement SQL SERVER

I am unsure of how to go about this problem.


I have three tables. bookcollection, books and users.



bookcollection bookc_id, bookc_bookid, bookc_bookuser
books bookid, title, author, year
users userid, username, password


bookid is foreign key to bookc_bookid


userid is a foreign key to bookc_bookuser


I have a c# winform and I am trying to insert a new book with textboxes. However, I've hit a wall. I am able to insert a new book into the books table. But, I also need to be able to insert the userid and the bookid into the bookcollection table so it would be in the user's book collection.


This is what I have.



private void add()
{
using (SqlConnection connection = new SqlConnection(constr))
{
SqlCommand cmd = new SqlCommand("INSERT INTO books (title, author, year) VALUES (@t, @a, @y)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("@t", title.Text);
cmd.Parameters.AddWithValue("@a", author.Text);
cmd.Parameters.AddWithValue("@y", year.Text);
connection.Open();
cmd.ExecuteNonQuery();
}


On the main form I have a string which is passed with username like public string Username;


Can anyone help me out with this? Would I need to create a stored procedure, if so how would I do this? Thanks in advance.


Aucun commentaire:

Enregistrer un commentaire