根据周获取日期名称的索引

时间:2018-01-22 11:08:12

标签: sql sql-server tsql

使用以下查询,我们可以获得今天工作日或特定日期的索引:

Select DATEPART(WEEKDAY, GETDATE())

但我需要知道日期名称的索引。就像我有Friday而我想获得6,我怎么能得到它?

更多澄清

我可以使用IF ... ELSE来实现结果,如下所示:

Declare @DayName varchar(50)
Declare @DayIndex int

set @DayName='Friday'

if @DayName='Saturday'
    set @DayIndex=7
else if @DayName='Friday'
    set @DayIndex=6

... so on

所以我的问题是:

问题:如果我使用上述方法,那么系统的任何regional settings中的日期索引是否相同?我指的是@@datefirst,在我的系统中它的值是7,如果它在其他系统中的值是1怎么办?

2 个答案:

答案 0 :(得分:3)

使用CASE声明

Declare @DayName varchar(50)
Declare @DayIndex int

set @DayName='Friday'

SELECT @DayIndex = CASE @DayName
                     WHEN 'Sunday' THEN 1
                     WHEN 'Monday' THEN 2
                     WHEN 'Tuesday' THEN 3
                     WHEN 'Wednesday' THEN 4
                     WHEN 'Thursday' THEN 5
                     WHEN 'Friday' THEN 6
                     ELSE 7
                   END 

答案 1 :(得分:1)

首先查看Pரதீப்的答案。您可以将其转换为这样的用户定义函数(考虑@@datefirst):

CREATE FUNCTION DayIndex(@DayName as varchar(50)) 
RETURNS INT AS 
BEGIN 
Declare @DayIndex int;
SELECT @DayIndex = CASE LOWER(@DayName)
                    WHEN 'sunday'   THEN    1+(7-@@datefirst)%7
                    WHEN 'monday'   THEN    1+(8-@@datefirst)%7
                    WHEN 'tuesday'  THEN    1+(9-@@datefirst)%7
                    WHEN 'wednesday'THEN    1+(10-@@datefirst)%7
                    WHEN 'thursday' THEN    1+(11-@@datefirst)%7
                    WHEN 'friday'   THEN    1+(12-@@datefirst)%7
                    WHEN 'saturday' THEN    1+(13-@@datefirst)%7
                   END;
RETURN @DayIndex;
END;

并像这样使用它:

SELECT [dbo].[DayIndex] ('Friday');

测试1:

set language US_ENGLISH;
select dbo.DayIndex('Sunday') Sunday
,dbo.DayIndex('Monday')    Monday
,dbo.DayIndex('Tuesday')   Tuesday
,dbo.DayIndex('Wednesday') Wednesday
,dbo.DayIndex('Thursday')  Thursday
,dbo.DayIndex('Friday')    Friday
,dbo.DayIndex('Saturday')  Saturday;
----- result -------
 Sunday Monday  Tuesday Wednesday   Thursday    Friday  Saturday
 1      2       3       4           5           6       7

测试2:

set language ITALIAN;
select dbo.DayIndex('Sunday') Sunday
,dbo.DayIndex('Monday')    Monday
,dbo.DayIndex('Tuesday')   Tuesday
,dbo.DayIndex('Wednesday') Wednesday
,dbo.DayIndex('Thursday')  Thursday
,dbo.DayIndex('Friday')    Friday
,dbo.DayIndex('Saturday')  Saturday;
----- result -----
Sunday  Monday  Tuesday Wednesday   Thursday    Friday  Saturday
7       1       2       3           4           5       6