如何制作触发器以检查用户选择的时间是否为空?

问题描述 投票:0回答:2
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 

sql sql-server triggers
2个回答
0
投票

您的触发器只是检查重复的值。最好使用unique约束:

alter table Schedule add constraint unq_schedule_ddate_st_time_end_time
    unique (ddate, st_time, end_time);

0
投票

由于您使用了触发器,所以我将以触发器格式回答。使用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

0
投票
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
© www.soinside.com 2019 - 2024. All rights reserved.