How to convert a datetime to string in T-SQL

前端 未结 9 1357
没有蜡笔的小新
没有蜡笔的小新 2020-12-13 03:19

I\'m surprised not to be able to find this question here already.

I have a date time var and I want to convert it to a string so that I can append it to another stri

相关标签:
9条回答
  • 2020-12-13 03:58
    SELECT CONVERT(varchar, @datetime, 103) --for UK Date format 'DD/MM/YYYY'
    

    101 - US - MM/DD/YYYY

    108 - Time - HH:MI:SS

    112 - Date - YYYYMMDD

    121 - ODBC - YYYY-MM-DD HH:MI:SS.FFF

    20 - ODBC - YYYY-MM-DD HH:MI:SS

    0 讨论(0)
  • 2020-12-13 03:59

    In addition to the CAST and CONVERT functions in the previous answers, if you are using SQL Server 2012 and above you use the FORMAT function to convert a DATETIME based type to a string.

    To convert back, use the opposite PARSE or TRYPARSE functions.

    The formatting styles are based on .NET (similar to the string formatting options of the ToString() method) and has the advantage of being culture aware. eg.

    DECLARE @DateTime DATETIME2 = SYSDATETIME();
    DECLARE @StringResult1 NVARCHAR(100) = FORMAT(@DateTime, 'g') --without culture
    DECLARE @StringResult2 NVARCHAR(100) = FORMAT(@DateTime, 'g', 'en-gb') 
    SELECT @DateTime
    SELECT @StringResult1, @StringResult2
    SELECT PARSE(@StringResult1 AS DATETIME2)
    SELECT PARSE(@StringResult2 AS DATETIME2 USING 'en-gb')
    

    Results:

    2015-06-17 06:20:09.1320951
    6/17/2015 6:20 AM
    17/06/2015 06:20
    2015-06-17 06:20:00.0000000
    2015-06-17 06:20:00.0000000
    
    0 讨论(0)
  • 2020-12-13 03:59

    This has been answered by a lot of people, but I feel like the simplest solution has been left out.

    SQL SERVER (I believe its 2012+) has implicit string equivalents for DATETIME2 as shown here

    Look at the section on "Supported string literal formats for datetime2"

    To answer the OPs question explicitly:

    DECLARE @myVar NCHAR(32)
    DECLARE @myDt DATETIME2
    SELECT @myVar = @GETDATE()
    SELECT @myDt = @myVar
    PRINT(@myVar)
    PRINT(@myDt)
    

    output:

    Jan 23 2019 12:24PM             
    2019-01-23 12:24:00.0000000
    

    Note: The first variable (myVar) is actually holding the value '2019-01-23 12:24:00.0000000' as well. It just gets formatted to Jan 23 2019 12:24PM due to default formatting set for SQL SERVER that gets called on when you use PRINT. Don't get tripped up here by that, the actual string in (myVer) = '2019-01-23 12:24:00.0000000'

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