如果“星期日”然后下一个立即日期n + 1一年,如何获得每个月的第n个日期。 例如:
Year=2014
nth value = 2(2nd of each month)
Date:
2014-01-02
2014-02-03 (since 02 is "Sunday" next Immediate date)
2014-03-03 (since 02 is "Sunday" next Immediate date)
2014-04-02
2014-05-02
2014-06-02
2014-07-02
and so on...
答案 0 :(得分:1)
怎么样,fiddle here
将使用'01'
和'28'
之间的日期值,我已将参数检查和转换保留为OP。
DECLARE @Year = Char(4);
DECLARE @Day = VarChar(2);
SET @Year = '2014';
SET @Day = '2';
SELECT
CASE DATENAME(dw, [Date])
WHEN 'Sunday' THEN DATEADD(d, 1, [Date])
ELSE [Date]
END [Date]
FROM (
SELECT
CAST(@Year + '-' + [M] + '-' + @Day AS DATETIME) [Date]
FROM (
SELECT '1' [M] 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 '8' UNION ALL
SELECT '9' UNION ALL
SELECT '10' UNION ALL
SELECT '11' UNION ALL
SELECT '12') [Months]) [RawDays];
答案 1 :(得分:0)
这对我有用......!
Declare @Tracker int
set @Tracker = 2
Declare @FromDate datetime
Declare @ToDate datetime
set @FromDate = '2014-01-01'
set @ToDate = '2014-12-31'
Declare @TrackerTable Table ( Date Datetime)
;with DateDifference As
(
SELECT @FromDate DateValue
UNION ALL
SELECT DateValue + 1
FROM DateDifference
WHERE DateValue + 1 < @ToDate
)
Insert into @TrackerTable
Select
Case
when datename(dw,DateValue) = 'Sunday' Then DateValue + 1
Else DateValue
End as Date
from DateDifference where Day(DateValue) = @Tracker
OPTION (MAXRECURSION 0)
Select * from @TrackerTable