Question: I have 3 tables in my sql database like these :

```
Documents : (DocID, FileName) //list of all docs that were attached to items
Items : (ItemID, ...) //list of all items
DocumentRelation : (DocID, ItemID) //the relation between docs and items

```

In my winform application I have showed all records of **Items** table in a grid view and let user to select several rows of it and then if he press EditAll button another grid view should fill by file name of documents that are related to these selected items but not all of them,

> 
> **Just each of documents which have relation with *ALL* selected items**
> 
> 
> 

Is there any query (*sql or linq*) to select these documents?

Answer: 
Try something like:

```
string query;
foreach (Item in SelectedItems)
{
   query += "select DocID from DocumentRelation where ItemID =" + Item.Id;
   query += "INTERSECT";
}
query -= "INTERSECT";

```

And exec the Query;
Linq

```
var td =
from s in Items
join r in DocumentRelation on s.ItemID equals r.ItemID
join k in Documents on k.DocID equals r.DocID
where Coll.Contains (s.ItemID)         //Here Coll is the collection of ItemID   which you can store when the users click on the grid view row
select new 
{
 FileName=k.FileName,
 DocumentID= k.DocId
 }; 

```

You can loop through td collection and bind to your grid view

SQL 

create a stored proc to get the relevant documents for the itemID selected from the grid view and paramterize your in clause

```
 select k.FileName,k.DocId from Items as s inner join 
 DocumentRelation as r on 
 s.ItemID=r.ItemID and r.ItemId in (pass the above coll containing selected ItemIds as an input the SP)
 inner join Documents as k
 on  k.DocId=r.DocIk 

```

You can get the information on [how to parametrize your sql query](https://stackoverflow.com/questions/337704/parameterizing-an-sql-in-clause)