简体   繁体   中英

Delete row from two sql tables that join together

There are two tables:

Table1 : UserID Name Job
Table2 : BookID Book Car UserID

I load these two tables in one wpf datagrid:

da.SelectCommand = new SqlCommand("select Table1.UserID, Table1.Name, Table1.Job, Table2.Book, Table2.Car from Table1 inner join Table2 on Table1.UserID = Table2.UserID");

I want to delete one row from Table2 by DataGrid:

 SqlCommand com = new SqlCommand("delete from Table2 where BookID=@BookID)",con);

but not work,

How can I do it?

You have to use the below way to delete the rows

DELETE FROM table2
WHERE  userid = (SELECT userid
                 FROM   table1);  

您是否期望这样的事情?

DELETE FROM B WHERE BOOKID IN (SELECT BOOKID FROM B,A WHERE B.USERID=A.USERID AND B.BOOK='ABCD'); 

You say "It must delete a book from a certain user not all books.". You have to know user id for which the books must be delete.

If you want to delete users books, do this:

delete from Table2 where userid in (user_id1,user_id1, etc .....); But you are large rows to delete, use bulk delete mechanism.

If you don't have user ids and have book ids, you have to do this:

Delete From Table2 where bookid in (book_id1,book_id2, etc ..); Or Delete From Table2 where bookid =? //according your development language, you set "?" parameter. I don't know C# syntaxe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM