如何验证这些列,我是否需要更复杂的触发器?

时间:2019-02-10 17:14:00

标签: sql sql-server tsql triggers

我正在尝试验证表ProjectDetails.TimeCards中的列

create table ProjectDetails.TimeCards(
    Time_Card_ID int identity (55,15),
    Employee_ID int foreign key references HumanResources.Employees(Employee_ID),
    Date_Issued date, --DateIssued should be greater than the current date and the project start date (Project start date is from another table). 
    Days_Worked int constraint chk_Days_Worked check(Days_Worked > '0'),
    Project_ID int foreign key references ProjectDetails.Projects(Project_ID),
    Billable_hours int constraint chk_Billable_Hours check (Billable_Hours > '0'),
    Total_Cost money, -- should be automatically calculated by using the following formula: TotalCost=Billable Hours * BillingRate (billing rate is from another table) 
    Work_Code_ID int foreign key references ProjectDetails.WorkCodes(Work_Code_ID)
    );

我尝试构建触发器,但是只有在Date_Issued小于当前日期时,才能触发触发器

CREATE TRIGGER dateissued
    ON ProjectDetails.TimeCards
    FOR INSERT
    AS
      DECLARE @ModifiedDate date
      SELECT @ModifiedDate = Date_Issued FROM Inserted
          IF (@ModifiedDate < getdate())
          BEGIN
            PRINT 'The modified date should be the current date. Hence, cannot insert.'
            ROLLBACK TRANSACTION -- transaction is to be rolled back
          END

如果发布的日期小于当前日期,并且发布的日期小于起始日期,则我需要触发触发器。至于计费率的计算,我迷路了。 这是另一个表

create table ProjectDetails.Projects(
    Project_ID int identity (0100, 01) primary key, -- Primary key
    Project_Name char (50) not null, 
    Start_Date date not null, -- the start date i'm referring to
    End_Date date not null,
    constraint CheckEndLaterThanStart check (End_Date > Start_Date),
    Billing_Estimate money constraint chk_Billing_Estimate check (Billing_Estimate > '1000'),
    Client_ID int Foreign Key references CustomerDetails.Clients(Client_ID)
);

1 个答案:

答案 0 :(得分:0)

我相信这提供了您所追求的逻辑。代码中有一些注释供您选择:

OptionalInt

请注意,您可能希望为CREATE TRIGGER trg_chk_Date_Issued ON ProjectDetails.TimeCards FOR INSERT, UPDATE --I assume on need on UPDATE as well, as otherwise this won't validate AS BEGIN IF EXISTS(SELECT 1 FROM inserted i JOIN ProjectDetails.Projects P ON i.Project_ID = P.Project_ID WHERE i.Date_Issued < CONVERT(date,GETDATE()) OR i.Date_Issued < P.Start_Date) BEGIN RAISERROR(N'Date Issued cannot be less than the current date or the Project Start Date.', 10,1); --Raised an error, rather than using PRINT ROLLBACK; END END 使用不同的触发器,就像您要更新行一样,并且UPDATE的值小于Date_Issued的日期,该语句将失败。