使用以下内容:
string strSelectSql = "SELECT Table1.ID, Table1.Status,
Table1.CustomerName,Table1.Date, Table1.LocationID,
Table2.LocationID As [LocationID 2] FROM Table1 LEFT JOIN
Table2 ON Table1.ID = Table2.ID
WHERE (Date Is Null AND ID= @SearchForString AND
Status != 'Archived') OR
((Date Between @FromDate AND @ToDate)
AND ID= @SearchForString AND Status != 'Archived')";
SqlConnection SqlConn = new SqlConnection(cstrDatabaseConnection);
SqlDataAdapter SqlAdpt = new SqlDataAdapter();
SqlCommand SqlCom = new SqlCommand(strSelectSql,SqlConn);
SqlCom.Parameters.AddWithValue("@SearchForString",strSearchString);
SqlCom.Parameters.AddWithValue("@FromDate",strFromDate);
SqlCom.Parameters.AddWithValue("@ToDate",strToDate );
SqlAdpt.SelectCommand = SqlCom;
try
{
DataSet TempDS = new DataSet();
SqlConn.Open();
SqlAdpt.Fill(TempDS);
SqlConn.Close();
SqlConn.Dispose();
if (Convert.ToInt32(TempDS.Tables[0].Rows.Count) > 0)
{
dgvQueryResult.DataSource = TempDS.Tables[0];
dgvQueryResult.Refresh();
dgvQueryResult.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
TempDS.Dispose();
}
}
catch (SqlException sqlE)
{
MessageBox.Show(sqlE.Message);
SqlConn.Close();
SqlConn.Dispose();
}
catch (Exception UnknownE)
{
MessageBox.Show(string.Format("Unknown Exception: {0}",UnknownE.Message);
SqlConn.Close();
SqlConn.Dispose();
}
finally
{
if (SqlConn != null) SqlConn.Dispose();
}
现在这一切都很好,除非 Table2 有多个 LocationID 值
Table2
+----+------------+
| ID | LocationID |
+----+------------+
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 4 |
| 5 | 5 |
| 6 | 6 |
| 6 | 7 |
| 6 | 7 |
| 7 | 8 |
| 7 | 9 |
+----+------------+
我想忽略:
Table2
+----+------------+
| ID | LocationID |
+----+------------+
| 6 | 7 |
| 6 | 7 |
+----+------------+
得到这个:
Table2
+----+------------+
| ID | LocationID |
+----+------------+
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
| 4 | 4 |
| 5 | 5 |
| 6 | 6 |
| 7 | 8 |
| 7 | 9 |
+----+------------+
但我确实想要:
Table2
+----+------------+
| ID | LocationID |
+----+------------+
| 6 | 6 |
+----+------------+
因为 LocationID 没有重复。
另外,我确实想要:
Table2
+----+------------+
| ID | LocationID |
+----+------------+
| 7 | 8 |
| 7 | 9 |
+----+------------+
再次因为 LocationID 不重复。
如果我必须这样做或者它会更有效,我也愿意在之前从 TempDS 中删除这些行:
dgvQueryResult.DataSource = TempDS.Tables[0];
如果即使需要或者最有效地从 dgvQueryResult 中删除条目