SQL Server过程以显示日期是工作日还是周末

时间:2018-09-16 21:06:29

标签: sql sql-server

我在SQL中遇到了很多麻烦,所以我很陌生,所以请原谅我。我创建了一个过程,该过程接受日期作为输入并在一年后,一周后和一天后打印原稿。现在,我想告诉我这些日期是输出中的工作日还是周末。我从“ Google搜索”中知道,它可能与DATETIMEDATENAME有关。希望你们提供一些指导。谢谢!

CREATE PROCEDURE dates 
AS
BEGIN
    DECLARE @startdate SMALLDATETIME;
    DECLARE @dateafteryear VARCHAR(50);
    DECLARE @weekafter VARCHAR(50);
    DECLARE @daylater VARCHAR(50);

    SET @startdate = GETDATE();
    SET @dateafteryear = DATEADD(YYYY, 1, @startdate)
    SET @weekafter = DATEADD(WEEK, 1, @startdate)
    SET @daylater = DATEADD(DAY, 1, @startdate)

    PRINT 'Original Date ' + CAST(@startdate AS VARCHAR);
    PRINT 'A year later ' + CAST(@dateafteryear AS VARCHAR);
    PRINT 'A week later ' + CAST(@weekafter AS VARCHAR);
    PRINT 'A day later ' + CAST(@daylater AS VARCHAR);
END
GO

EXEC dates;

输出:

Original date Jan 12 2015 4:47PM, **is a Weekday.**
A year later Jan 12 2016 4:47PM, **is a Weekday.**
A week later Jan 19 2015 4:47PM, **is a Weekday.**
A day later Sep 17 2018 4:50 PM, **is a Weekday.**

3 个答案:

答案 0 :(得分:2)

在SQL Server中将DATEPART(在标准SQL中为EXTRACT)与weekday参数一起使用(可以缩写为dw)。请注意,weekdaydw都是语言关键字,而不是字符串值,例如:DATEPART( weekday, @startDate )

此函数从int返回1的{​​{1}}值对应于星期几。请注意,实际的天数映射取决于您的7上下文值,例如在美国,星期日是一周的第一天(DATEFIRST =星期日),但在世界上大多数地方是星期一(1 =星期一)。建议您在致电1之前,先指定SET DATEFIRST与所需的值。

因此,要确定日期是否是周末,请执行以下操作:

DATEPART( weekday, ... )

文档:

答案 1 :(得分:1)

我确定这是一个思想实验,但我从未在PRINT中看到太多价值。我也看到很多重复。

也许为了简洁起见。 :)

示例

DECLARE @startdate SMALLDATETIME;
SET @startdate = GETDATE();

Select comment = Concat(prefix,dt,'. *** is a ',case when DateName(WEEKDAY,dt) in ('Saturday','Sunday') then 'Weekend' else 'Weekday' end,'.**')
 From  ( values ( @startdate                  ,'Original Date ')
               ,( DateAdd(YEAR, 1, @startdate),'A Year Later ' )
               ,( DateAdd(WEEK, 1, @startdate),'A Week Later ' )
               ,( DateAdd(DAY , 1, @startdate),'A day later '  )
       ) A (dt,prefix)

返回

comment
Original Date Sep 16 2018  4:55PM. *** is a Weekend.**
A Year Later Sep 16 2019  4:55PM. *** is a Weekday.**
A Week Later Sep 23 2018  4:55PM. *** is a Weekend.**
A day later Sep 17 2018  4:55PM. *** is a Weekday.**

很有趣,如果您真的想打印

DECLARE @startdate SMALLDATETIME;
SET @startdate = GETDATE();

Declare @Print varchar(max) = (
Select Concat(prefix,dt,'. *** is a ',case when DateName(WEEKDAY,dt) in ('Saturday','Sunday') then 'Weekend' else 'Weekday' end,'.**',char(10))
 From  ( values ( @startdate                  ,'Original Date ')
               ,( DateAdd(YEAR, 1, @startdate),'A Year Later ' )
               ,( DateAdd(WEEK, 1, @startdate),'A Week Later ' )
               ,( DateAdd(DAY , 1, @startdate),'A day later '  )
       ) A (dt,prefix)
 For XML Path('')
)
Print @Print

答案 2 :(得分:0)

我将theme函数与geom_text一起使用,以检查星期几还是周末。

  • ggplot(df, aes(x, y, label = label)) + geom_text() + theme(text = element_text(size = 42))
  • base_size

我将编写一个函数DATEPART来检查日期。

CASE WHEN

您的过程可以使用

Saturday = 1

sqlfiddle