简体   繁体   English

如何在视图中使datepart()函数接受星期一作为一周的第一天

[英]How to make a datepart() function in a view accept Monday as the first day of the week

For a webapplication I created the following view: 对于一个Web应用程序,我创建了以下视图:

alter view [dbo].[vwBookingData] 
as
    select concat(rtrim(ltrim(str(datepart(year, bookingdata.booking_datetime)))), '-', rtrim(ltrim(str(datepart(week, bookingdata.booking_datetime))))) as  WeekNumber, 
           bookingdata.booking_customerCode as ClientCode, customer.Name as ClientName, concat(bookingdata.booking_provider, concat('-', bookingdata.booking_system)) as ProviderCombo,
           bookingdata.segments_carrierCode as CarrierCode, bookingdata.booking_datetime as BookingDate, bookingdata.booking_bookingId, flgConfirmed, flgFailed
    from dbo.flights_bookingdata bookingdata
         inner join dbo.Customer on Customer.Number = bookingdata.booking_customerCode

My problem is 1 specific part of the used query: 我的问题是所用查询的1个特定部分:

datepart(week, bookingdata.booking_datetime)

I have noticed the datepart() appears to take a week starts on Sunday rather than on Monday, this breaks the overview the view is supposed to generate. 我已经注意到datepart()似乎需要在周日开始而不是在星期一开始,这打破了视图应该生成的概述。

Is there a way I can fix this within the query itself? 有没有办法可以在查询本身中解决此问题?

Perhaps you can try (I was right first with 1 not 2) 也许您可以尝试(我首先是1而不是2)

SET DATEFIRST 1;

At the top of your query 在查询的顶部

SET DATEFIRST 7;  -- The Default
Select *
      ,WeedDay=DateName(DW,RetVal)
      ,WeekNo=DatePart(WK,RetVal) 
 From [dbo].[udf-Range-Date]('2016-10-01','2016-10-14','DD',1)

在此处输入图片说明

While

SET DATEFIRST 1;
Select *
      ,WeedDay=DateName(DW,RetVal)
      ,WeekNo=DatePart(WK,RetVal) 
 From [dbo].[udf-Range-Date]('2016-10-01','2016-10-14','DD',1)

在此处输入图片说明

看到您无法使用SET DATEFIRST选项,我将在调用DATEPART函数时从日期时间中减去一天,如下所示:

DATEPART(WEEK, DATEADD(DAY, -1, bookingdata.booking_datetime))

With this function you can return the day of the week, starting from monday, in any server language or DATEFIRST setting: 使用此功能,您可以从星期一开始以任何服务器语言或DATEFIRST设置返回星期几:

-- =============================================
-- Author:      Javier Cañon
-- Create date: 2019-04-23
-- Description: Return day of week without know of server SET DATEFIRST setting
-- =============================================
CREATE FUNCTION [dbo].[fnGetWeekDayFromMonday]
(
    -- Add the parameters for the function here
    @SomeDate DATE
)
RETURNS int
AS
BEGIN

DECLARE @SqlWeekDay INT, @ResultVar int;

    SET  @SqlWeekDay= DATEPART(dw, @SomeDate);
    SET @ResultVar = ((@SqlWeekDay + @@DATEFIRST - 1 - 1) % 7) + 1;

    -- Return the result of the function
    RETURN @ResultVar;

END
GO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM