我是ASP.NET MVC和Sql Server的新手 尝试插入表1的第二步以从表1列y更新表2列x。 更新其问题会更新整个列x
我的桌子: 台式车 (CarId 汽车模型 颜色 牌照板 里程表)
表JobInfo (作业ID 工作号 日期 开始位置 目的地 里程表 内径计 停车处 CarId 用户ID)
更新Car Set CarOdometer =(从JobInfo中选择TOP 1 EndOdometer,其中CarId =通过EndOdometer DESC排序Car.CarId ORDER)
从JobInfo更新Car set Car.CarOdometer = JobInfo.EndOdometer,其中JobInfo.carId =(SELECT IDENT_CURRENT(JobInfo.CarId));
试图使用内部联接但不起作用
string query1 = "INSERT INTO JobInfo (JobNum,Date,StartLocation,Destination,EndOdometer,Parking,CarId,StartOdometer)" +
"VALUES(@JobNum,@Date,@StartLocation,@Destination,@EndOdometer,@Parking,@CarId,@StartOdometer)";
string query2 = "Update Car SET Car.CarOdometer = (Select top 1 JobInfo.EndOdometer FROM JobInfo INNER JOIN Car ON JobInfo.CarId = Car.CarId "+
"ORDER BY JobInfo.EndOdometer desc) WHERE Car.CarId = Car.CarId";
sqlCon.Open();
var sqlCmd1 = new SqlCommand(query1, sqlCon);
var sqlCmd2 = new SqlCommand(query2, sqlCon);
sqlCmd1.Parameters.AddWithValue("@JobNum", jobModel.JobNum);
sqlCmd1.Parameters.AddWithValue("@Date", jobModel.Date.ToString());
sqlCmd1.Parameters.AddWithValue("@StartLocation", jobModel.StartLocation);
sqlCmd1.Parameters.AddWithValue("@Destination", jobModel.Destination);
sqlCmd1.Parameters.AddWithValue("@EndOdometer", jobModel.EndOdometer);
sqlCmd1.Parameters.AddWithValue("@Parking", Convert.ToDecimal(jobModel.Parking));
sqlCmd1.Parameters.AddWithValue("@CarId", Convert.ToInt32(jobModel.CarId));
sqlCmd1.Parameters.AddWithValue("@StartOdometer", Convert.ToInt32(jobModel.StartOdometer));
//Updating CarOdometer from EndOdometer
sqlCmd2.Parameters.AddWithValue("@CarOdometer", Convert.ToInt32(jobModel.CarOdometer));
sqlCmd1.ExecuteNonQuery();
sqlCmd2.ExecuteNonQuery();
仅更新CarId = 1中的CarOdometer或将取决于CarId的CarOdometer应该更改,而不是所有记录
谢谢您的时间
答案 0 :(得分:0)
如果除了JobInfo表中包含的那些记录外,您无需更改所有记录,可以对其进行检查:
UPDATE Car SET CarOdometer = (SELECT TOP 1 EndOdometer FROM JobInfo
WHERE CarId = Car.CarId ORDER BY EndOdometer DESC)
WHERE EXISTS (SELECT TOP 1 EndOdometer FROM JobInfo
WHERE CarId = Car.CarId ORDER BY EndOdometer DESC)