Is there a way to get dates with custom formats in SQL Server?

后端 未结 2 1979
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-26 21:55

In Oracle, you can use:

SELECT to_char(sysdate, \'yyyy-mm\') FROM dual;

to show just the year and month portion of a date. Additionally, you ca

相关标签:
2条回答
  • 2021-01-26 22:39

    Currently the best option is to have a CLR function that is a wrapper to .NET's DateTime.ToString(string format).

    If you don't want a separate function, you can build the required string from pieces:

    YEAR(@d) + '-' + MONTH(@d) + '-' + DAY(@d)
    

    As for the definite solution, there will be a formatting function in the next version of SQL Server.

    0 讨论(0)
  • 2021-01-26 22:41

    It depends on what version of SQL Server you are using.

    SQL Server 2005, 2008, and 2008 R2

    For these versions you would need to make use of SQLCLR to expose that functionality from .NET. You can either write your own SQLCLR function using the DateTime class (as noted in @GSerg's answer), or you can simply download and install the Free version of SQL# (which I am the author of, but the Date_Format function is free).

    Example:

    SELECT SQL#.Date_Format(GETDATE(), 'ffffdd in MMMM', '') AS [Default_language],
           SQL#.Date_Format(GETDATE(), 'ffffdd in MMMM', 'he') AS [Hebrew],
           SQL#.Date_Format(GETDATE(), 'ffffdd in MMMM', 'de') AS [German];
    

    Returns:

    Default_language      Hebrew               German
    Monday in January     יום שני in ינואר    Montag in Januar
    

    SQL Server 2012 and newer

    Use the built-in FORMAT function.

    Example:

    SELECT FORMAT(GETDATE(), 'ffffdd in MMMM') AS [Default_language],
           FORMAT(GETDATE(), 'ffffdd in MMMM', 'he') AS [Hebrew],
           FORMAT(GETDATE(), 'ffffdd in MMMM', 'de') AS [German];
    

    Returns:

    Default_language      Hebrew               German
    Monday in January     יום שני in ינואר    Montag in Januar
    

    For both SQLCLR and built-in FORMAT options

    The following two MSDN pages detail the available formatting options:

    • Custom Date and Time Format Strings
    • Standard Date and Time Format Strings
    0 讨论(0)
提交回复
热议问题