SQL如果记录存在更新,如果不存在则插入

时间:2015-06-02 18:44:25

标签: sql-server

我有一个像这样的SQL查询:

cmd = new SqlCommand(@"UPDATE Reservations 
                                    SET ReservationsID = (SELECT PersonID FROM People WHERE Name = @Name) WHERE 
                                    SchedulePersonID = (SELECT SchedulePersonID FROM SchedulePerson WHERE (ScheduleID = (SELECT ScheduleID FROM Schedule WHERE Store_No = @StoreNo)) 
                                    AND LibraryTaskID = @Task)");

我要做的是,如果记录不存在,请插入它。如果记录不存在,我想将ReservationsID和SchedulePersonID插入该表。我在网上看过一些例子,但我不明白。请帮忙。

1 个答案:

答案 0 :(得分:1)

cmd = new SqlCommand(@"UPDATE Reservations 
SET ReservationsID = (SELECT PersonID FROM People WHERE Name = @Name) 
WHERE SchedulePersonID = (SELECT SchedulePersonID FROM SchedulePerson   
WHERE (ScheduleID = 
 (SELECT ScheduleID FROM Schedule WHERE Store_No = @StoreNo)) 
                                    AND LibraryTaskID = @Task)");

不会做你想做的事,但最重要的是Insert != Update。也就是说,你必须做一个或另一个,因为语法不同。

Insert Table(Fields...) Values(FieldValues...)
Update Table set Fields=Values,... Conditions

伪代码

SqlCommand command = new SqlCommand(selectQueryWithFieldsYouWantToUpdateOrInsertInOneTable,connection);
SqlAdapter adapter = new SqlAdapter(command)
SqlCommandBuilder builder = new SqlCommandBuilder(adapter)
DataSet dataset = adapter.Fill(table,"tableName")
DataTable datatable = dataset.tables["tableName"];
if(datatable.Rows.Count == 1) {
  DataRow row = datatable.rows[0];
  row.Field["fieldName"] = fieldValue;
  adapter.update(datatable);
}
else if (datatable.Rows.Count == 0) {
  DataRow row = datatable.NewRow();
  // row.Field["fieldName"] = fieldValue;
  datatable.Rows.Add(row);
  adapter.update(datatable);
}
else {
  multiple rows match conditions...
}