如何获得星期六的日期。今天和我约会。
GETDATE()
如何做到这一点。
例如。今天是08-08-2011
我希望输出为08-13-2011
答案 0 :(得分:4)
如果你这样称呼它,这个函数会在下周六返回:
SELECT dbo.fn_Get_NextWeekDay('2011-08-08', 6)
“6”来自the list of possible values,您可以为DATEFIRST
设置。
您可以通过相应地更改第二个参数来获得一周中的任何其他日子。
这是功能:
IF OBJECT_ID('dbo.fn_Get_NextWeekDay') IS NOT NULL
DROP FUNCTION dbo.fn_Get_NextWeekDay
GO
CREATE FUNCTION dbo.fn_Get_NextWeekDay(
@aDate DATETIME
, @dayofweek INT
/*
@dw - day of the week
1 - Monday
2 - Tuesday
3 - Wednesday
4 - Thursday
5 - Friday
6 - Saturday
7 - Sunday
*/
)
RETURNS DATETIME
AS
/*
SELECT dbo.fn_Get_NextWeekDay('2011-08-08', 6)
SELECT dbo.fn_Get_NextWeekDay('2011-08-08', 1)
*/
BEGIN
RETURN
DATEADD(day
, ( @dayofweek + 8 - DATEPART(dw, @aDate) - @@DATEFIRST ) % 7
, @aDate
)
END
GO
<强> [编辑] 强> 这可能是另一种解决方案。这应该适用于任何语言:
IF OBJECT_ID('dbo.fn_NextWeekDay') IS NOT NULL
DROP FUNCTION dbo.fn_NextWeekDay
GO
CREATE FUNCTION dbo.fn_NextWeekDay(
@aDate DATE
, @dayofweek NVARCHAR(30)
)
RETURNS DATE
AS
/*
SELECT dbo.fn_NextWeekDay('2016-12-14', 'fri')
SELECT dbo.fn_NextWeekDay('2016-03-15', 'mon')
*/
BEGIN
DECLARE @dx INT = 6
WHILE UPPER(DATENAME(weekday,@aDate)) NOT LIKE UPPER(@dayofweek) + '%'
BEGIN
SET @aDate = DATEADD(day,1,@aDate)
SET @dx=@dx-1
if @dx < 0
BEGIN
SET @aDate = NULL
BREAK
END
END
RETURN @aDate
END
GO
答案 1 :(得分:3)
DECLARE @Today date = 'TODAYS-DATE';
DECLARE @TodayNumber int = DATEPART(dw, @Today) -- Get the day number
DECLARE @Saturday date = DATEADD(DAY, (6-@TodayNumber)%7, @Today)
-- Add the number of days between today and saturday (the 6th day), modulus 7 to stop you adding negative days
希望有所帮助!
答案 2 :(得分:3)
使用Calendar表(每个日期有一行的表):
SELECT MIN(DateValue) DateValue
FROM Calendar
WHERE DateValue >= CURRENT_TIMESTAMP
AND DayOfWeek = 'Saturday';
答案 3 :(得分:2)
使用DATEPART获取今天的星期几,并将差异添加到所需的星期几到今天的日期。
答案 4 :(得分:1)
答案 5 :(得分:1)
试试这个:
SET DATEFIRST 7
DECLARE @d DATETIME
SET @d = '2011-08-08' --GETDATE()
SELECT NEXT_SAT = DATEADD(day, (7 + @@DATEFIRST - DATEPART(dw, @d)) % 7, @d )
答案 6 :(得分:1)
另一种方法需要两个步骤,但可能更具可读性(看起来不大,没有模数):
DATEADD(DAY, -1 * datepart(weekday, GETDATE()), getdate())
DATEADD(WEEK, 1, @lastSaturday, getdate()))
整个事情:
declare @today DATETIME = GETDATE()
declare @lastSaturday DATETIME = DATEADD(DAY, -1 * datepart(weekday, @today), @today)
declare @nextSaturday DATETIME = DATEADD(WEEK, 1, @lastSaturday)
或者,如果您认为@today
是GETDATE()
,则可以一次执行所有计算:
SELECT DATEADD(WEEK, 1, DATEADD(DAY, -1 * datepart(weekday, GETDATE()), getdate()))