datetime2 Data Type

Overview

The datetime2 data type is used to store date and time values. It is a superset of the older datetime and smalldatetime data types. datetime2 supports a larger date range, higher precision, and is ANSI SQL compliant.

Key Features of datetime2:

Using datetime2 is generally recommended over datetime and smalldatetime for new development due to its enhanced capabilities and compliance with SQL standards.

Syntax

When declaring a datetime2 variable or column, you can specify the fractional seconds precision.

SQL Server Syntax
datetime2(fractional_seconds_precision)

Parameters:

Storage Requirements:

Precision (fractional_seconds_precision) Storage Size (Bytes)
0 6
1-2 7
3-4 8
5-7 9

Behavior

The datetime2 data type stores date and time values independently of the server's time zone. This means that if you insert a date and time value on a server in one time zone, it will be stored exactly as provided, regardless of the client's time zone.

Date and Time Components:

A datetime2 value consists of the following components:

Implicit Conversion:

datetime2 can be implicitly converted to and from various string literals and other date/time data types. However, explicit conversion is often preferred for clarity and to avoid unexpected behavior.

Note: When converting from older date/time types (like datetime) to datetime2, precision may be lost if the source type has lower precision.

Performance Considerations

While datetime2 offers significant advantages, consider the following for performance:

Examples

Declaring a Variable with Default Precision:

SQL Server Example
DECLARE @MyDateTime2 datetime2;
SET @MyDateTime2 = '2023-10-27 10:30:15.1234567';
PRINT @MyDateTime2;

Declaring a Variable with Specific Precision:

SQL Server Example
DECLARE @MyDateTime2WithPrecision datetime2(3); -- Precision of 3 decimal places for seconds
SET @MyDateTime2WithPrecision = '2023-10-27 10:30:15.123';
PRINT @MyDateTime2WithPrecision;

Inserting into a Table:

SQL Server Example
CREATE TABLE SampleDateTime2 (
    EventID INT PRIMARY KEY IDENTITY(1,1),
    EventName VARCHAR(100),
    EventTimestamp datetime2(6) -- Stores up to 6 decimal places for seconds
);

INSERT INTO SampleDateTime2 (EventName, EventTimestamp)
VALUES ('System Startup', GETDATE()); -- GETDATE() returns current datetime

INSERT INTO SampleDateTime2 (EventName, EventTimestamp)
VALUES ('User Login', '2023-10-27 14:05:00.123456');

SELECT * FROM SampleDateTime2;