Overview
SQL Server provides several data types for storing dates and times. Understanding these data types is crucial for working with temporal data effectively. These types allow you to perform operations like adding or subtracting intervals, calculating date differences, and formatting dates and times for display.
Key Date and Time Data Types
Here’s a breakdown of the most common date and time data types:
- datetime: Stores both date and time values.
- smalldatetime: Stores date and time values with a smaller precision.
- datetime2: Offers higher precision than datetime and is generally the preferred choice.
- datetimeoffset: Stores date, time, and a time zone offset.
- date: Stores only the date portion.
- time: Stores only the time portion.
Example Code
Here are some examples demonstrating how to use these data types:
CREATE TABLE MyTable (
ID INT IDENTITY(1,1) PRIMARY KEY,
OrderDate datetime2
);
INSERT INTO MyTable (OrderDate) VALUES ('2023-10-27 10:30:00');
SELECT OrderDate FROM MyTable;