一个SQL存储过程,用于获取两种不同截止日期格式的截止日期

时间:2017-02-15 08:28:52

标签: tsql sql-server-2008-r2

我有一个从两个客户端数据库读取的系统。对于这两个客户,他们都有不同的截止日期格式:

1)客户A:每个月15日。示例:15-12-2016。

2)客户B:每月的第一天。示例:1-1-2017。

截止日期存储在表格中,如下所示: enter image description here

现在我需要一个查询来检索当前月份客户端的截止日期。例如,今天是15-2-2017,因此两个客户的预期截止日期应如下:

1)客户A:15-1-2017

2)客户B:1-2-2017

如何在单个存储过程中完成此操作?对于客户B,我总是可以获得该月的第一天。但这不适用于客户A,因为他们的截止日期是上个月的日期。

1 个答案:

答案 0 :(得分:0)

你可能正在寻找这样的东西:

DECLARE @DummyClient TABLE(ID INT IDENTITY,ClientName VARCHAR(100));
DECLARE @DummyDates TABLE(ClientID INT,YourDate DATE);
INSERT INTO @DummyClient VALUES
 ('A'),('B');
INSERT INTO @DummyDates VALUES 
 (1,{d'2016-12-15'}),(2,{d'2017-01-01'});

WITH Numbers AS
(          SELECT 0 AS Nr
 UNION ALL SELECT 1
 UNION ALL SELECT 2
 UNION ALL SELECT 3
 UNION ALL SELECT 4
 UNION ALL SELECT 5
 UNION ALL SELECT 6
 UNION ALL SELECT 7
 UNION ALL SELECT 9
 UNION ALL SELECT 10
 UNION ALL SELECT 11
 UNION ALL SELECT 12
 UNION ALL SELECT 13
 UNION ALL SELECT 14
 UNION ALL SELECT 15
 UNION ALL SELECT 16
 UNION ALL SELECT 17
 UNION ALL SELECT 18
 UNION ALL SELECT 19
 UNION ALL SELECT 20
 UNION ALL SELECT 21
 UNION ALL SELECT 22
 UNION ALL SELECT 23
 UNION ALL SELECT 24
 ) 
,ClientExt AS
(
    SELECT c.*
          ,MIN(d.YourDate) AS MinDate
    FROM @DummyClient AS c
    INNER JOIN @DummyDates AS d ON c.ID=d.ClientID
    GROUP BY c.ID,c.ClientName
)
SELECT ID,ClientName,D
FROM ClientExt
CROSS APPLY(SELECT DATEADD(MONTH,Numbers.Nr,MinDate)
            FROM Numbers) AS RunningDate(D);

结果

ID  Cl  Date
1   A   2016-12-15
1   A   2017-01-15
1   A   2017-02-15
1   A   2017-03-15
1   A   2017-04-15
1   A   2017-05-15
1   A   2017-06-15
1   A   2017-07-15
1   A   2017-09-15
1   A   2017-10-15
1   A   2017-11-15
1   A   2017-12-15
1   A   2018-01-15
1   A   2018-02-15
1   A   2018-03-15
1   A   2018-04-15
1   A   2018-05-15
1   A   2018-06-15
1   A   2018-07-15
1   A   2018-08-15
1   A   2018-09-15
1   A   2018-10-15
1   A   2018-11-15
1   A   2018-12-15
2   B   2017-01-01
2   B   2017-02-01
2   B   2017-03-01
2   B   2017-04-01
2   B   2017-05-01
2   B   2017-06-01
2   B   2017-07-01
2   B   2017-08-01
2   B   2017-10-01
2   B   2017-11-01
2   B   2017-12-01
2   B   2018-01-01
2   B   2018-02-01
2   B   2018-03-01
2   B   2018-04-01
2   B   2018-05-01
2   B   2018-06-01
2   B   2018-07-01
2   B   2018-08-01
2   B   2018-09-01
2   B   2018-10-01
2   B   2018-11-01
2   B   2018-12-01
2   B   2019-01-01