Search code examples
sql-date-functionssqldatetime

how to convert GETDATE() in a SQL database for a specific format while creating table?


How can i create a convert function while creating a table, my following sql script for creating table is.

CREATE TABLE database.dbo.Machine
   (HistoryID bigint IDENTITY(1,1) PRIMARY KEY,
    MachineId bigint,
    HistoryDate datetime2(0) DEFAULT GETDATE(),
  );
GO

This above code gives me the datetime format in yyyy-mm-dd HH:mm:ss I need to convert this GETDATE() in HH:mm:ss dd-mm-yyyy, i can use a query SELECT FORMAT(GETDATE(),'HH:mm:ss dd-mm-yyyy') But how can include this while creating a table script itself in my above script. Thank you.


Solution

  • Try using CONVERT with appropriate format masks:

    SELECT
        CONVERT(varchar, GETDATE(), 108) + ' ' + CONVERT(varchar, GETDATE(), 105) AS ts;
    

    enter image description here

    Demo