ALTER TRIGGER [dbo].[Check_time] on [dbo].[Schedule] after insert
AS
if exists ((select * from Schedule as S Join inserted as i on S.DDate=i.DDate AND S.ST_TIME=i.ST_TIME AND S.END_TIME=i.END_TIME))
BEGIN
print('INVALID TIME')
ROLLBACK TRANSACTION
return
END
您的触发器只是检查重复的值。最好使用unique
约束:
alter table Schedule add constraint unq_schedule_ddate_st_time_end_time
unique (ddate, st_time, end_time);
由于您使用了触发器,所以我将以触发器格式回答。使用INSTEAD OF代替插入后。在这种情况下,请在设置记录之前检查表。使用2作为建议
ALTER TRIGGER [dbo].[Check_time]
ON [dbo].[Schedule]
INSTEAD OF INSERT
AS
BEGIN
DECLARE @Count INT = 0
SELECT @Count = COUNT(*)
FROM Schedule AS S
INNER JOIN inserted AS i ON S.DDate=i.DDate AND S.ST_TIME=i.ST_TIME AND S.END_TIME=i.END_TIME
IF ISNULL(@Count , 0) = 0
BEGIN
INSERT INTO [dbo].[Schedule] ([MID], [SID], [ST_TIME], [END_TIME], [DDate], [ST_ID])
select [MID], [SID], [ST_TIME], [END_TIME], [DDate], [ST_ID] FROM inserted
END
END
ALTER TRIGGER [dbo].[Check_time]
ON [dbo].[Schedule]
INSTEAD OF INSERT
AS
BEGIN
DECLARE @Count INT = 0
SELECT @Count = COUNT(*)
FROM Schedule AS S
INNER JOIN inserted AS i ON S.DDate=i.DDate AND S.ST_TIME=i.ST_TIME AND S.END_TIME=i.END_TIME
IF ISNULL(@Count , 0) = 0
BEGIN
INSERT INTO [dbo].[Schedule] ([MID], [SID], [ST_TIME], [END_TIME], [DDate], [ST_ID])
select [MID], [SID], [ST_TIME], [END_TIME], [DDate], [ST_ID] FROM inserted
END
END