How to convert a datetime to string in T-SQL

前端 未结 9 1356
没有蜡笔的小新
没有蜡笔的小新 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:39

    There are 3 different methods depending on what I is my requirement and which version I am using.

    Here are the methods..

    1) Using Convert

    DECLARE @DateTime DATETIME = GETDATE();
    --Using Convert
    SELECT
        CONVERT(NVARCHAR, @DateTime,120) AS 'myDateTime'
        ,CONVERT(NVARCHAR(10), @DateTime, 120) AS 'myDate'
        ,RIGHT(CONVERT(NVARCHAR, @DateTime, 120),8) AS 'myTime'
    

    2) Using Cast (SQL Server 2008 and beyond)

    SELECT
        CAST(@DateTime AS DATETIME2) AS 'myDateTime'
        ,CAST(@DateTime AS DATETIME2(3)) AS 'myDateTimeWithPrecision'
        ,CAST(@DateTime AS DATE) AS 'myDate'
        ,CAST(@DateTime AS TIME) AS 'myTime'
        ,CAST(@DateTime AS TIME(3)) AS 'myTimeWithPrecision'
    

    3) Using Fixed-length character data type

    DECLARE @myDateTime NVARCHAR(20) = CONVERT(NVARCHAR, @DateTime, 120);
    DECLARE @myDate NVARCHAR(10) = CONVERT(NVARCHAR, @DateTime, 120);
    
    SELECT
        @myDateTime AS 'myDateTime'
        ,@myDate AS 'myDate'
    
    0 讨论(0)
  • 2020-12-13 03:43

    You can use the convert statement in Microsoft SQL Server to convert a date to a string. An example of the syntax used would be:

    SELECT convert(varchar(20), getdate(), 120)
    

    The above would return the current date and time in a string with the format of YYYY-MM-DD HH:MM:SS in 24 hour clock.

    You can change the number at the end of the statement to one of many which will change the returned strings format. A list of these codes can be found on the MSDN in the CAST and CONVERT reference section.

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

    There are many different ways to convert a datetime to a string. Here is one way:

    SELECT convert(varchar(25), getdate(), 121)  – yyyy-mm-dd hh:mm:ss.mmm
    

    See Demo

    Here is a website that has a list of all of the conversions:

    How to Format datetime & date in SQL Server

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

    Try below :

    DECLARE @myDateTime DATETIME
    SET @myDateTime = '2013-02-02'
    
    -- Convert to string now
    SELECT LEFT(CONVERT(VARCHAR, @myDateTime, 120), 10)
    
    0 讨论(0)
  • 2020-12-13 03:49

    Check CAST and CONVERT syntax of t-sql:

    http://msdn.microsoft.com/en-us/library/ms187928.aspx

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

    The following query will get the current datetime and convert into string. with the following format
    yyyy-mm-dd hh:mm:ss(24h)

    SELECT convert(varchar(25), getdate(), 120) 
    
    • SQLFiddle Demo
    • SQL Server Date Formats
    0 讨论(0)
提交回复
热议问题