2012-11-30 583 views
0
recid | EffectiveFrom | EffectiveTo 
------------------------------------ 
    1 | 2012-11-25 | 2012-11-30 
    2 | 2012-11-26 | null 

我需要檢查,如果新的日期落在effectivefromeffectiveTo 之間並停止插入觸發..SQL Server中,INSERT觸發器

+0

如果你有100行 - **我們應該檢查哪些**'effectiveFrom'和'effectiveTo'?他們全部?而且:新插入行的哪一列**不允許落入這兩個日期之間?您需要提供更多信息! –

+1

你有什麼嘗試?還是你希望有人編寫你可以複製和使用的代碼? – Raj

+0

請參閱:[觸發器簡介 - 第1部分](http://www.sqlteam.com/article/an-introduction-to-triggers-part-i)或僅在Google或Bing上搜索**!有**數千**的介紹性文章... http://bit.ly/U5Qq7U –

回答

0

試試這個:

USE {yourDB}; 

CREATE TRIGGER insertRecord ON {tblName} 
INSTEAD OF INSERT 
AS 
BEGIN 
    DECLARE @EffectiveFrom DATE; 
    DECLARE @EffectiveTo DATE; 
    DECLARE @newDate DATE; 
    SET @newDate = GETDATE(); -- DATE WHICH YOU WANT TO CHEK 
    SELECT @EffectiveFrom = EffectiveFrom FROM INSERTED; 
    SELECT @EffectiveTo = EffectiveTo FROM INSERTED; 

    IF (@newDate > @EffectiveFrom AND @newDate < @EffectiveTo) 
     BEGIN 
     INSERT INTO [{yourDB}].[dbo].[{tblName}] 
     SELECT * FROM INSERTED; 
     PRINT 'DATA SUCCESSFULLY ADDED.' 
     END 
    ELSE PRINT 'ERROR : DATE IS NOT IN BETWEEN EffectiveFrom and EffectiveTo DATE' 
END 


INSERT INTO [{yourDB}].[dbo].[{tblName}] VALUES(CAST('24-NOV-2012' AS DATE),CAST('30-NOV-2012' AS DATE)) 

消息 - 結果 錯誤:日期不在有效生效日期和生效日期之間

INSERT INTO [{yourDB}].[dbo].[{tblName}] VALUES(CAST('24-NOV-2012' AS DATE),CAST('02-DEC-2012' AS DATE)) 

消息 - 結果 (1 row(s)affected) 數據已成功添加。

+1

如果INSERT語句恰好插入**多行**,那麼這是** NOT **開始工作;你會怎樣'SELECT @EffectiveFrom = EffectiveFrom FROM INSERTED;'真的選擇?正在檢查10個插入的行中的哪一個? SQL Server中的觸發器被稱爲**每批**一次(可能多於一行!)和「插入」可以包含1,5,10,100行。觸發器是** NOT **每行被觸發 –

+0

是的,它的true..it將一次插入單行。 –

+0

......但感謝我得到了解決方案,並啓動並運行.. – user1666443