0

我想从另一个表(员工)中填充我的表(即将到来的生日),那里会有 DOB,并且在传递 DOB 时应该删除表中的数据。我的表(即将到来的生日)属性为“Employee_Code”、“Name”、“DOB”、“Days_left_to_Birthday”、“Mobile_Number”、“Email”

在这里,当任何行的“Days_left_to_Birthday”变为“0”时,该行应该自动从表中删除(即将到来的生日)。

我搜索了它,但找不到它。

4

1 回答 1

0

此示例显示生日在 1 个月内的员工:

CREATE TABLE dbo.Employees 
(
    EmployeesID INT IDENTITY(1,1) PRIMARY KEY,
    FirstName   NVARCHAR(50) NOT NULL,
    LastName    NVARCHAR(50) NOT NULL,
    Birthday    DATETIME NOT NULL
);
INSERT  dbo.Employees (FirstName, LastName, Birthday)
VALUES  (N'A', N'X', '19950114'), 
        (N'B', N'Y', '19900915'),
        (N'D', N'Z', '19901016'),       
        (N'E', N'T', '19901117'),
        (N'F', N'V', '19891218');
GO      

CREATE VIEW dbo.vEmployeeWithNextBirthday
AS
SELECT  e.*,
        CASE
            WHEN    e.NextBirthday1 > GETDATE() 
            AND     e.NextBirthday1 <= DATEADD(MONTH, +1, GETDATE()) THEN   e.NextBirthday1
            WHEN    e.NextBirthday2 > GETDATE() 
            AND     e.NextBirthday2 <= DATEADD(MONTH, +1, GETDATE()) THEN   e.NextBirthday2
        END AS NextBirthday
FROM
(       
SELECT  e.EmployeesID, e.FirstName, e.LastName, e.Birthday,
        DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) - DATEDIFF(YEAR, 0, e.Birthday), e.Birthday) AS NextBirthday1,
        DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) - DATEDIFF(YEAR, 0, e.Birthday) + 1, e.Birthday) AS NextBirthday2
FROM    dbo.Employees e
) src
GO  

SELECT * FROM dbo.vEmployeeWithNextBirthday;
GO

结果:

EmployeesID FirstName LastName Birthday   NextBirthday1 NextBirthday2 NextBirthday
----------- --------- -------- ---------- ------------- ------------- -----------------------
1           A         X        1995-01-14 2013-01-14    2014-01-14    NULL
2           B         Y        1990-09-15 2013-09-15    2014-09-15    NULL
3           D         Z        1990-10-16 2013-10-16    2014-10-16    2013-10-16 -- <-- My current date is 2013-09-29
4           E         T        1990-11-17 2013-11-17    2014-11-17    NULL
5           F         V        1989-12-18 2013-12-18    2014-12-18    NULL

此查询显示生日在 1 个月内的员工:

SELECT * FROM dbo.vEmployeeWithNextBirthday v
WHERE v.NextBirthday IS NOT NULL;
GO

使用另一个当前日期的另一个测试:

DECLARE @CurrentDate DATETIME;
SET     @CurrentDate = '20131215';

SELECT  *,
        CASE
            WHEN    src.NextBirthday1 > @CurrentDate 
            AND     src.NextBirthday1 <= DATEADD(MONTH, +1, @CurrentDate) THEN  src.NextBirthday1
            WHEN    src.NextBirthday2 > @CurrentDate 
            AND     src.NextBirthday2 <= DATEADD(MONTH, +1, @CurrentDate) THEN  src.NextBirthday2
        END AS NextBirthday
FROM
(       
SELECT  *,
        DATEADD(YEAR, DATEDIFF(YEAR, 0, @CurrentDate) - DATEDIFF(YEAR, 0, e.Birthday), e.Birthday) AS NextBirthday1,
        DATEADD(YEAR, DATEDIFF(YEAR, 0, @CurrentDate) - DATEDIFF(YEAR, 0, e.Birthday) + 1, e.Birthday) AS NextBirthday2
FROM    dbo.Employees e
) src
于 2013-09-29T11:46:29.427 回答