0

我需要创建触发器以防止插入和更新到 21 岁以下和 67 岁以上的表员工,代码的下一步是什么?

CREATE TRIGGER allowInsertUpdateemployee ON dbo.employee
    AFTER UPDATE, INSERT 

AS
BEGIN
DECLARE @v_ageLow INT = 21,
        @v_ageHigh  INT = 67,
        @v_dateLow date,
        @v_dateHigh date

SET @v_dateLow = DATEADD(YEAR, -1 * @v_ageLow, GETDATE())
SET @v_dateHigh = DATEADD(YEAR, -1 * @v_ageHigh, GETDATE())



END     
4

4 回答 4

2

由于上限和下限是固定的,因此检查约束可能是比触发器更合适的解决方案

ALTER TABLE employee ADD CONSTRAINT ck_employee_age CHECK 
(DateOfBirth BETWEEN DATEADD(YEAR,-67,GETDATE()) AND DATEADD(YEAR,-21,GETDATE()))
于 2013-10-03T11:19:18.573 回答
1
  1. Use "INSTEAD OF INSERT, UPDATE" trigger;
  2. Use INSERTED table to check new incoming values, raiserror if needed;
  3. Use DELETED table to detect if update is processing (this can help);
  4. Do manual insert or update then (if needed).

    INSERT INTO dbo.employee SELECT * FROM INSERTED I

于 2013-10-03T11:30:52.390 回答
0

我希望这样做
这不会获取准确的年龄,但是如果您的方法为您提供准确的日期,您可以使用您的代码。

或者

您还可以使用以下代码来获取年龄:

SELECT DATEDIFF(Day,'2011-11-03' , GETDATE()) /365

选择日期(日期,@年龄,GETDATE())/ 365

 CREATE TRIGGER allowInsertUpdateemployee ON dbo.employee
      INSTEAD OF Insert 

    AS
    BEGIN
    DECLARE @v_ageLow INT,
            @v_ageHigh  INT,
            @v_date date,
          --@v_dateHigh date

    SET @v_ageLow  = SELECT DATEDIFF(Year,@v_date  , GETDATE())
    SET @v_ageHigh = SELECT DATEDIFF(Year,@v_date  , GETDATE())
    BEGIN
            if(@v_ageLow <21  AND @v_ageHigh >67)
            BEGIN
                RAISERROR('Cannot Insert or Update where User is not in age limit);
                ROLLBACK;
            END

            ELSE

                 BEGIN 

             // else write your insert update query
                Insert into values ()
                PRINT 'Unable to Insert-- Instead Of Trigger.'
            END    

    END  
于 2013-10-03T11:56:42.540 回答
0

你必须OR输入where条款。员工不得低于 21 岁且不得超过 67 岁。

Create TRIGGER tr_Too_young_or_too_old 
ON TableName
AFTER INSERT
AS
if exists ( select *, DATEDIFF(yy, birthdate, GETDATE()) as age 
            from TableName
where DATEDIFF(yy, birthdate, GETDATE()) < 21 or DATEDIFF(yy, birthdate, GETDATE()) > 67 )
begin
    rollback
    RAISERROR ('Cannot Insert or Update where User is not in age limit', 16, 1);
end
于 2017-08-25T07:32:24.970 回答