如何在一个月内获得星期五的日期
问题描述:
如何在一个月内获得星期五的约会?假设7月份有4个星期五。我想要检索日期。我不使用任何数据库表。请帮帮我。
How can I get Friday dates in a month? Suppose in July there are 4 Friday. I want to retrieve the dates. I don't use any database table. Please help me.
答
试试这个.. :)
try this.. :)
declare @DateFrom datetime,@DateTo datetime
set @DateFrom='23 Mar 2014'
set @DateTo='26 Jun 2014'
;WITH CTEQuery AS (
SELECT CAST(@DateFrom AS DATETIME) AS dt
UNION ALL
SELECT DATEADD(dd, 1, dt)
FROM CTEQuery s
WHERE DATEADD(dd, 1, dt) <= CAST(@DateTo AS DATETIME)
),sampleData as(
select dt,datename(WEEKDAY,dt)as [DayName] from CTEQuery )
select * from sampleData where [DayName]='Friday'
你必须从代码后面传递@ DateFrom
和@ DateTo
,你将ge那些星期五之间的日期日期..:)
you have to just pass @DateFrom
and @DateTo
from code behind and you will get all friday dates between there dates.. :)
首先,我假设你'使用 SQL Server 。这是一个示例(查询应该在 SQL Server 2005 或更高版本中工作):
Hi,
First of all, I'm assuming that you're using SQL Server. Here's an example (the query should work in SQL Server 2005 or above):
DECLARE @Year VARCHAR(4),
@Month VARCHAR(3),
@FirstDate DATETIME,
@LastDate DATETIME;
SET @Year = '2014';
SET @Month = '07'; -- '07' or 'Jul'
SET @FirstDate = (SELECT CAST(( @Year + @Month + '01' ) AS DATETIME));
SET @LastDate = DATEADD(DAY, -1, ( DATEADD(MONTH, 1, @FirstDate) ));
;WITH Fridays([Date])
AS (SELECT [Date] = @FirstDate
UNION ALL
SELECT [Date] = DATEADD(DAY, 1, [Date])
FROM Fridays
WHERE [Date] < @LastDate)
SELECT [Date]
FROM Fridays
WHERE DATENAME(WEEKDAY, [Date]) = 'Friday';
注意:考虑到输入参数和 SQL Server 的版本,可以(应该)改进此查询。
结果:
Note: This query could (should) be improved considering your input parameters and version of the SQL Server.
Result:
Date
2014-07-04 00:00:00.000
2014-07-11 00:00:00.000
2014-07-18 00:00:00.000
2014-07-25 00:00:00.000
如果您需要进一步帮助,请与我们联系。
Please let me know if you need further assistance.
DECLARE @StartDate date = '2014-07-01'
DECLARE @EndDate date = '2014-07-31'
CREATE TABLE #tblGetFriday ([Friday] Date)
WHILE @StartDate <> CONVERT(date,@EndDate)
BEGIN
IF((SELECT UPPER(DATENAME(dw, @StartDate))) = 'FRIDAY')
BEGIN
INSERT INTO #tblGetFriday SELECT @StartDate As Fridays
END
SET @StartDate = DATEADD(Day,1,@StartDate)
END
SELECT * FROM #tblGetFriday
DROP TABLE #tblGetFriday