Creating date in SQL Server 2008

前端 未结 3 1949
天命终不由人
天命终不由人 2021-02-07 01:23

Is there something similar to DATEFROMPARTS(year, month, day) in SQL Server 2008? I want to create a date using the current year and month, but my own day of the mo

相关标签:
3条回答
  • 2021-02-07 01:38

    Using the 3 from your example, you could do this:

    dateadd(dd, 3 -1, dateadd(mm, datediff(mm,0, current_timestamp), 0))
    

    It works by finding the number of months since the epoch date, adding those months back to the epoch date, and then adding the desired number of days to that prior result. It sounds complicated, but it's built on what was the canonical way to truncate dates prior to the Date (not DateTime) type added to Sql Server 2008.

    You're probably going to see other answers here suggesting building date strings. I urge you to avoid suggestions to use strings. Using strings is likely to be much slower, and there are some potential pitfalls with alternative date collations/formats.

    0 讨论(0)
  • 2021-02-07 01:50

    You could use something like this to make your own datetime:

    DECLARE @year INT = 2012
    DECLARE @month INT = 12
    DECLARE @day INT = 25
    
    SELECT CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @month) + '-' + CONVERT(VARCHAR, @day)
     AS DATETIME)
    
    0 讨论(0)
  • 2021-02-07 01:51
    CREATE FUNCTION  DATEFROMPARTS
    (
        @year int,
        @month int,
        @day int
    )
    RETURNS datetime
    AS
    BEGIN
    
         declare @d datetime
    
         select @d =    CAST(CONVERT(VARCHAR, @year) + '-' + CONVERT(VARCHAR, @month) + '-' + CONVERT(VARCHAR, @day) AS DATETIME)
        RETURN  @d 
    
    END
    GO
    
    0 讨论(0)
提交回复
热议问题