How do you print the day name given a day number in SQL Server 2005 using SQL commands?

前端 未结 4 1991
臣服心动
臣服心动 2021-01-14 10:17

I want to be able to pass in a day number like 1, 2, 3 or 7 and it will return the day name like Sunday, Monday, Tuesday or Saturday. I know there is the option of using a <

相关标签:
4条回答
  • 2021-01-14 10:39
    SELECT DATENAME(DW,CAST(a AS INT))
    

    Here we can change the value of a as 0 to 6
    Default, 0-Monday to 6- Sunday.
    If we use a=7 then it will be calculated as 0, because 7-7=0.

    0 讨论(0)
  • 2021-01-14 10:42

    SQL Server Denali has the CHOOSE function that will make this more concise. In the meantime just use CASE inside the UDF.

    CREATE FUNCTION dbo.WeekDay(@d int)
    RETURNS VARCHAR(9)
    WITH SCHEMABINDING, RETURNS NULL ON NULL INPUT
    AS
    BEGIN
    RETURN 
    (
    SELECT 
        CASE @d
            WHEN 1 THEN 'Sunday'
            WHEN 2 THEN 'Monday'
            WHEN 3 THEN 'Tuesday'
            WHEN 4 THEN 'Wednesday'
            WHEN 5 THEN 'Thursday'
            WHEN 6 THEN 'Friday'
            WHEN 7 THEN 'Saturday'
        END
    )
    END
    
    0 讨论(0)
  • 2021-01-14 10:47

    Try this :

    declare @m varchar 
    set @m=1 
    SELECT DATENAME(DW,CAST(@m AS INT))
    
    0 讨论(0)
  • 2021-01-14 10:49
    CREATE FUNCTION dbo.udf_DayOfWeek(@dtDate DATETIME)
    RETURNS VARCHAR(10)
    AS
    BEGIN
    DECLARE @rtDayofWeek VARCHAR(10)
    SELECT @rtDayofWeek = CASE DATEPART(weekday,@dtDate)
    WHEN 1 THEN 'Sunday'
    WHEN 2 THEN 'Monday'
    WHEN 3 THEN 'Tuesday'
    WHEN 4 THEN 'Wednesday'
    WHEN 5 THEN 'Thursday'
    WHEN 6 THEN 'Friday'
    WHEN 7 THEN 'Saturday'
    END
    RETURN (@rtDayofWeek)
    END
    GO
    
    -- Call this function like this:
    SELECT dbo.udf_DayOfWeek(GETDATE()) AS DayOfWeek
    

    orignally from : SQL SERVER – UDF – Get the Day of the Week Function

    0 讨论(0)
提交回复
热议问题