这是我的代码,它创建带有一些查询结果的dataTables:
private void executerRequete(string requete, string description, string niveauAlerte)
{
RequetesSQLResult res = new RequetesSQLResult();
res.Description = description;
string StSQL = requete;
res.Results=new DataTable();
try
{
using (SqlConnection _oConnection = new SqlConnection(_dataService.ParamGlobaux.ConnectionString))
{
SqlCommand command = new SqlCommand(StSQL, _oConnection);
command.Parameters.AddWithValue("@mat", _dataService.ParamGlobaux.StMatricule);
command.Parameters.AddWithValue("@dd", dateDebut);
command.Parameters.AddWithValue("@df", datefin);
_oConnection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
var row = res.Results.NewRow();
Object[] values = new Object[reader.FieldCount];
int fieldCount = reader.GetValues(values);
if (res.Results.Columns.Count == 0)
{
for (int i = 0; i < reader.FieldCount; i++)
{
res.Results.Columns.Add(new DataColumn(reader.GetName(i)));
}
}
for (int i = 0; i < reader.FieldCount; i++)
{
row[i] = values[i];
}
res.Results.Rows.Add(row);
}
}
}
}
catch (Exception x)
{
Debug.WriteLine(x.Message + ":" + x.StackTrace);
}
if (res.Results.Rows.Count > 0)
{
Results.Add(res);
}
}
}
我的问题是循环到达此处:
res.Results.Columns.Add(新的DataColumn(reader.GetName(i)));
只要我只使用一张桌子,一切都很好。当我使用两个或多个表时,出现错误消息“列[i]已存在”。
示例:
SELECT * FROM Contrats X, Contrats Y
WHERE x.Avenant = 'CONTRAT' AND y.Avenant = 'CONTRAT' AND X.Matricule = Y.Matricule AND x.[Num Contrat] != y.[Num Contrat] AND
((x.[Date début] < y.[Date Fin] AND x.[Date Fin] > Y.[Date début]) OR
(x.[Date début] > y.[Date début] AND y.[Date Fin] IS NULL) OR
(x.[Date début] < y.[Date début] AND y.[Date Fin] IS NULL))
AND x.Matricule = @mat
=>错误将是:“列'Name'已经存在”,因为它被读取了两次(每个表一个)。
如果它们具有相同的名称,我如何只保留一列?
您可以在添加列之前检查是否存在同名列:
string name = reader.GetName(i);
if (!res.Results.Columns.Contains(name))
res.Results.Columns.Add(new DataColumn(name));
在那种情况下,您不应该使用SELECT *
,而必须使用SELECT Column1, Column2,.. Column n
SELECT Column1, Column2,.. Column n
FROM Contrats X, Contrats Y
WHERE x.Avenant = 'CONTRAT' AND y.Avenant = 'CONTRAT' AND X.Matricule = Y.Matricule AND x.[Num Contrat] != y.[Num Contrat] AND
((x.[Date début] < y.[Date Fin] AND x.[Date Fin] > Y.[Date début]) OR
(x.[Date début] > y.[Date début] AND y.[Date Fin] IS NULL) OR
(x.[Date début] < y.[Date début] AND y.[Date Fin] IS NULL))
AND x.Matricule = @mat