我正在尝试为数据库中的某些记录创建一个insert语句。
因此DataTable
可以返回100行,但在foreach
循环中,它会在第一行中运行插入100次。我希望在DataTable
中的每一行都运行插入。
string status = @"select j.*, " +
" (SELECT Status FROM jobstat WHERE jobstat.JobID = j.ID ORDER BY Sequence DESC LIMIT 0,1) AS CurrentStatusCode " +
" from job_new j " +
" left join jobstat js on js.jobid=j.id " +
" where j.delivermemberid=j.jobownerid and j.jobdate= '2016-05-20' " +
" and j.isactive=1 and j.IsOnManifest = 1 " +
" Group by j.ID " +
" HAVING CurrentStatusCode NOT IN ('DEL' )";
DataTable dtStatus = BaseDisplaySet.CustomFill(status, param);
DataSet dsStat = new DataSet();
dsStat.Tables.Add(dtStatus);
if (dsStat.Tables[0].Rows.Count > 0)
{
foreach (DataRow dr in dtStatus.Rows)
{
string InsertStatusSQL = @"INSERT INTO jobstat (JobID,CompanyID,Status,Descrip,Sequence,CompCode,StatusID,StatusDate,Comment1,Comment2, CreateMethod)
VALUES (" + int.Parse(dtStatus.Rows[0]["ID"].ToString()) + ", 171 , '" + dtStatusfield.Rows[0]["StatusCode"].ToString() + "' , '" + dtStatusfield.Rows[0]["Text"].ToString() + "' , '" + dtStatusfield.Rows[0]["ListOrder"].ToString() +
"' ,0 , '" + int.Parse(dtStatusfield.Rows[0]["ID"].ToString()) + "' , '" + DateTime.Now + "' ,'WebService', '' , 'WebService')";
BaseDisplaySet.CustomNonQuery(InsertStatusSQL, param);
}
}
我也试过了foreach (DataRow dr in dsStat.Tables[0].Rows)
,但这也不起作用。它仍然只更新了第一行。
答案 0 :(得分:1)
看起来您应该使用 dataRow 而不是 dtStatus.Rows [0] 。你根本就不使用foreach循环。
foreach (DataRow dataRow in dtStatus.Rows)
{
string InsertStatusSQL = @"INSERT INTO jobstat (JobID,CompanyID,Status,Descrip,Sequence,CompCode,StatusID,StatusDate,Comment1,Comment2, CreateMethod)
VALUES (" + int.Parse(dataRow["ID"].ToString()) + ", 171 , '" + dataRow["StatusCode"].ToString() + "' , '" + dataRow["Text"].ToString() + "' , '" + dataRow["ListOrder"].ToString() +
"' ,0 , '" + int.Parse(dataRow["ID"].ToString()) + "' , '" + DateTime.Now + "' ,'WebService', '' , 'WebService')";
BaseDisplaySet.CustomNonQuery(InsertStatusSQL, param);
}
答案 1 :(得分:1)
使用变量dr
代替dtStatus.Rows[0]
,如:
foreach (DataRow dr in dtStatus.Rows)
{
string InsertStatusSQL = @"INSERT INTO jobstat (JobID,CompanyID,Status,Descrip,Sequence,CompCode,StatusID,StatusDate,Comment1,Comment2, CreateMethod)
VALUES (" + int.Parse(dr["ID"].ToString()) + ", 171 , '" + dr ["StatusCode"].ToString() + "' , '" + dr["Text"].ToString() + "' , '" + dr ["ListOrder"].ToString() +
"' ,0 , '" + int.Parse(dr["ID"].ToString()) + "' , '" + DateTime.Now + "' ,'WebService', '' , 'WebService')";
BaseDisplaySet.CustomNonQuery(InsertStatusSQL, param);
}