[英]How to make a datepart() function in a view accept Monday as the first day of the week
對於一個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
我的問題是所用查詢的1個特定部分:
datepart(week, bookingdata.booking_datetime)
我已經注意到datepart()似乎需要在周日開始而不是在星期一開始,這打破了視圖應該生成的概述。
有沒有辦法可以在查詢本身中解決此問題?
也許您可以嘗試(我首先是1而不是2)
SET DATEFIRST 1;
在查詢的頂部
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)
而
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))
使用此功能,您可以從星期一開始以任何服務器語言或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.