我考虑过使用 distinct 但我不太确定如何将它作为单个查询来提高代码效率,有什么办法吗?我基本上是在尝试检查是否已经存在数据条目,我正在尝试使用 BookingTime 进行检查。谢谢:)
这是我的 SQL 查询:
string bookingInfo = "INSERT INTO Booking(BookingDate, BookingTime, CustomerID, EmployeeID, ServiceType, BookingLength) " +
"VALUES (@BookingDate, @BookingTime, @CustomerID, @EmployeeID, @ServiceType, @BookingLength) " +
"where not exists (SELECT 1 FROM Booking WHERE BookingTime = @BookingTime)";
我收到的错误:“附加信息:查询输入必须至少包含一个表或查询。”
最佳答案
最好的办法是让数据库来做校验。
在表上创建唯一索引或约束:
create unique index unq_booking_bookingtime on booking(bookingtime);
注意:这是基于您的查询。在我看来,只有 bookingtime
定义唯一性似乎不太可能。
如果遇到重复项,数据库将生成错误。您可以使用 insert ignore
或 insert on duplicate key update
来防止错误(后者是首选方法)。
关于c# - 仅当数据不存在时如何将数据添加到表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36601927/