If条件

时间:2016-03-28 05:04:19

标签: sql-server

我编写此查询以将数据插入 Att_process checkin_time 字段。

如果 CHECKINOUT CHECKTIME 字段小时值< 12,它应插入 CHECKINOUT checkin_time 字段。 如果它大于12,则应插入 CHECKINOUT checkout_time 字段

但它不起作用,你能帮我解决这个问题吗?我也不知道怎么把它放在触发器上,如果你可以帮助我,我会非常感激。

IF (DATEPART(HOUR,CHECKTIME) < 12) 
BEGIN
    INSERT INTO Att_process(USERID,checkin_time)
    SELECT CHECKINOUT.USERID,CHECKINOUT.CHECKTIME
    from CHECKINOUT 
    where DATEPART(HOUR,CHECKTIME) < 12; 
END
ELSE
BEGIN
    INSERT INTO Att_process(USERID,checkout_time)
    SELECT CHECKINOUT.USERID,CHECKINOUT.CHECKTIME
    from CHECKINOUT 
    where DATEPART(HOUR,CHECKTIME) >= 12;
END

2 个答案:

答案 0 :(得分:1)

Plz试试这个

INSERT INTO Att_process(USERID,checkin_time,checkout_time)
SELECT USERID, 
    (CASE WHEN DATEPART(HOUR,CHECKTIME) < 12 THEN CHECKTIME END),
    (CASE WHEN DATEPART(HOUR,CHECKTIME) >= 12 THEN CHECKTIME END)
FROM CHECKINOUT 

答案 1 :(得分:0)

U可以使用此触发器只需相应地更改脚本

CREATE TRIGGER trgAfterInsert ON [dbo].[CHECKINOUT]
FOR INSERT
AS
     DECLARE @uid INT;
     DECLARE @checkin DATETIME;
     SELECT @uid = i.USERID
     FROM [CHECKINOUT] i;
     SELECT @checkin = i.CHECKTIME
     FROM [CHECKINOUT] i;
     IF(DATEPART(HOUR, @checkin) < 12)
         BEGIN
             INSERT INTO Att_process
                                    (USERID, checkin_time
                                    )
             VALUES
                    (@uid, @checkin
                    );
         END;
     ELSE
         BEGIN
             INSERT INTO Att_process
                                    (USERID, checkout_time
                                    )
             VALUES
                    (@uid, @checkin
                    );
         END;