📅  最后修改于: 2023-12-03 15:35:04.743000             🧑  作者: Mango
SQL Server Datetime refers to the date and time data types supported by Microsoft SQL Server. These data types are used to represent date and time values in a range of formats.
SQL Server supports several datetime data types, including:
Datetime: This data type is used to represent a date and time value. It has a range from January 1, 1753, to December 31, 9999, with an accuracy of 3.33 milliseconds.
Datetime2: This data type is similar to the Datetime data type, but has a higher accuracy and a larger date range. It has a range from January 1, 0001, to December 31, 9999, with an accuracy of 100 nanoseconds.
Datetimeoffset: This data type is used to represent a date and time value with an offset from Coordinated Universal Time (UTC). It has a range from January 1, 0001, to December 31, 9999, with an accuracy of 100 nanoseconds.
Smalldatetime: This data type is similar to Datetime, but has a smaller range and a lower accuracy. It has a range from January 1, 1900, to June 6, 2079, with an accuracy of 1 minute.
SQL Server provides several built-in functions for working with date and time data types, including:
GETDATE(): This function returns the current date and time value.
DATEPART(): This function extracts a specific part of a date and time value, such as the year, month, or day.
DATEDIFF(): This function returns the difference between two date and time values, such as the number of days, hours, or minutes.
DATEADD(): This function adds a specified interval to a date and time value, such as adding a number of days, months, or years.
Here is an example code snippet that uses SQL Server Datetime data types and functions:
-- Create a table to store datetime values
CREATE TABLE DatetimeExample
(
ID INT IDENTITY(1,1) PRIMARY KEY,
DatetimeColumn DATETIME,
Datetime2Column DATETIME2,
DatetimeoffsetColumn DATETIMEOFFSET,
SmalldatetimeColumn SMALLDATETIME
)
-- Insert some datetime values into the table
INSERT INTO DatetimeExample (DatetimeColumn, Datetime2Column, DatetimeoffsetColumn, SmalldatetimeColumn)
VALUES ('2022-01-01 12:34:56', '2022-01-01 12:34:56.7890123', '2022-01-01 12:34:56.1234567 +02:00', '2022-01-01 12:34:00')
-- Query the table and perform some date and time calculations
SELECT ID, DatetimeColumn, DATEPART(year, DatetimeColumn) AS Year, DATEDIFF(day, DatetimeColumn, GETDATE()) AS DaysAgo, DATEADD(month, 1, SmalldatetimeColumn) AS NextMonth
FROM DatetimeExample
WHERE DatetimeoffsetColumn > '2022-01-01 12:00:00'
This code creates a table to store datetime values, inserts some sample data, and then queries the table to perform some date and time calculations using SQL Server functions. The output will be in a table format.