如何检查表中是否存在特定记录

时间:2018-12-13 10:56:48

标签: sql-server

我有一个表,其中存储了多个日期,这些日期是员工的出勤日期

CREATE TABLE Attendance
(
EmpCode INT,
AttendanceDate DATETIME
)

INSERT INTO Attendance VALUES (24, '2018-12-01');
INSERT INTO Attendance VALUES (24, '2018-12-02');
INSERT INTO Attendance VALUES (24, '2018-12-03');
INSERT INTO Attendance VALUES (24, '2018-12-04');
INSERT INTO Attendance VALUES (24, '2018-12-06');

现在,由于该员工没有保存日期,因此在这种情况下应显示为缺席。

SELECT * FROM Attendance

1 个答案:

答案 0 :(得分:1)

如果要插入,它将给出表中该emp的错过日期,您可以使用现有代码插入

CREATE TABLE #Attendance
(
EmpCode INT,
AttendanceDate DATETIME
)

INSERT INTO #Attendance VALUES (24, '2018-12-01');
INSERT INTO #Attendance VALUES (24, '2018-12-02');
INSERT INTO #Attendance VALUES (24, '2018-12-03');
INSERT INTO #Attendance VALUES (24, '2018-12-04');
INSERT INTO #Attendance VALUES (24, '2018-12-06');

select * from #Attendance

 ;WITH CTE AS
    (
    SELECT CONVERT(DATE,'2018-12-01') AS DATE1
    UNION ALL
    SELECT DATEADD(DD,1,DATE1) FROM CTE WHERE DATE1<'2018-12-06'
    )
    --insert into #Attendance(EmpCode,AttendanceDate)
    SELECT DATE1 MISSING_ONE,'a' FROM CTE
    EXCEPT 
    SELECT AttendanceDate,'a' FROM #Attendance
    option(maxrecursion 0)