跳到正文
DEV Community· Son Tran·· 47 分鐘前AI 評分51

SQL Server DATETIME 與 DATETIME2 如何選擇,以及轉換既有欄位的成本

SQL Server DATETIME vs DATETIME2: Which to Use, and What Converting an Existing Column Costs

AI 導讀

文章比較 SQL Server 的 DATETIME 與 DATETIME2,建議新欄位使用 DATETIME2(3),以 7 bytes 儲存精確毫秒;DATETIME 則佔 8 bytes,按 1/300 秒步進取整。

正文

Disclosure: I build Schemity, a desktop ERD tool - this post is from our blog and uses it for the examples.

TL;DR: Use DATETIME2(3) for new columns: it keeps exact milliseconds in 7 bytes, while DATETIME rounds to steps of 1/300 second in 8. Converting an existing column means dropping its default and indexes first, then a rewrite of every row under a schema lock, about 1.4 seconds and 106 MB of log on one million rows in our test. Pick a precision of 3 or more, or the conversion rounds stored values without an error.

For a new SQL Server column, use DATETIME2(3): it keeps exact milliseconds in 7 bytes, where DATETIME rounds every value to a step of 1/300 second and takes 8. The harder question is the column you already have. Converting DATETIME to DATETIME2 is safe for the data at a precision of 3 or more, but the ALTER COLUMN is refused until its default and indexes are gone, then rewrites every row under a lock that blocks reads unless it runs online, and a precision below 3 rounds stored values without a word.

Everything below ran on SQL Server 2022 (CU26, Developer edition) in a throwaway container under x86 emulation on a laptop, so read the timings as proportions, not as what your server will do.

What does DATETIME actually store?

DATETIME stores time in steps of 1/300 second, so the last digit of the milliseconds is always 0, 3 or 7.

The DATETIME documentation says values are "rounded to increments of .000, .003, or .007 seconds", and opens with "Avoid using datetime for new work." Inserting the same literals into each type shows what that means:

Literal DATETIME DATETIME2(3) DATETIME2(0) SMALLDATETIME
10:00:00.001 10:00:00.000 10:00:00.001 10:00:00 10:00
10:00:00.005 10:00:00.007 10:00:00.005 10:00:00 10:00
10:00:29.500 10:00:29.500 10:00:29.500 10:00:30 10:00
23:59:59.999 next day 00:00:00.000 23:59:59.999 next day 00:00:00 next day 00:00

The last row is the one that reaches production. A report that filters a day with WHERE created_at BETWEEN '2026-11-22' AND '2026-11-22 23:59:59.999' on a DATETIME column includes every row stamped at midnight the next day, because the upper bound itself rounds to 2026-11-23 00:00:00.000. The half-open form, created_at >= '2026-11-22' AND created_at < '2026-11-23', is correct on every type.

SQL Server DATETIME vs DATETIME2: which should you use?

Use DATETIME2, with a precision chosen on purpose rather than the default of 7.

DATETIME DATETIME2(3) DATETIME2(7) SMALLDATETIME
Steps 1/300 s 1 ms 100 ns 1 minute
Bytes (measured with DATALENGTH) 8 7 8 4
Earliest date 1753-01-01 0001-01-01 0001-01-01 1900-01-01
@d + 1 adds a day Yes No, Msg 206 No, Msg 206 Yes
Matching default function GETDATE() SYSDATETIME() SYSDATETIME() GETDATE()

The DATETIME2 documentation gives 6 bytes for a precision under 3, 7 bytes for 3 or 4, and 8 for the rest, and a bare DATETIME2 is DATETIME2(7): sys.columns reported precision 27, scale 7 for it. For most columns DATETIME2(3) gives exact values in less space than the type it replaces. Choose 7 when the application compares the stored value with its own in-memory copy: a .NET DateTime holds 100-nanosecond ticks, and Entity Framework Core maps it to datetime2(7) by default. If the column must record which offset a time was written in, DATETIMEOFFSET adds it in 10 bytes at the default precision.

DATETIME keeps one advantage, and it is a liability: integer arithmetic. DECLARE @d datetime = '2026-11-22'; SELECT @d + 1 returns the next day, while the same expression on DATETIME2 fails with Msg 206, "Operand type clash: datetime2 is incompatible with int". Any code that does integer arithmetic on the column itself, such as created_at + 1, needs DATEADD before the conversion. GETDATE() - 7 keeps working, because GETDATE() still returns DATETIME.

What breaks when you convert DATETIME to DATETIME2?

Three things: the ALTER COLUMN itself until you clear the way, integer arithmetic on the column, and equality comparisons between the two types.

Start with a table most systems have, one million orders with a default and an index on the timestamp:

CREATE TABLE orders (
  id int IDENTITY PRIMARY KEY,
  customer_id int NOT NULL,
  created_at datetime NOT NULL CONSTRAINT df_orders_created_at DEFAULT GETDATE(),
  note varchar(50) NOT NULL DEFAULT ''
);
CREATE INDEX ix_orders_created_at ON orders (created_at);

The obvious statement, ALTER TABLE orders ALTER COLUMN created_at datetime2(3) NOT NULL;, returns:

Msg 5074, Level 16, State 1
The object 'df_orders_created_at' is dependent on column 'created_at'.
Msg 5074, Level 16, State 1
The index 'ix_orders_created_at' is dependent on column 'created_at'.
Msg 4922, Level 16, State 9
ALTER TABLE ALTER COLUMN created_at failed because one or more objects access this column.

The default constraint blocks it as surely as the index does. WITH (ONLINE = ON) was accepted once both were gone, but with the index still in place it failed with the same Msg 5074, as the ALTER TABLE documentation warns: online ALTER COLUMN "doesn't reduce the restrictions on when a column can be altered." The same page explains why NOT NULL is restated in every ALTER COLUMN here: a column altered without it becomes nullable.

The comparison change is the quiet one. Since SQL Server 2016, at database compatibility level 130 and above, a DATETIME converted to DATETIME2 keeps its true fraction, so the stored .003 becomes .0033333. With a table ev whose DATETIME column at holds 2026-11-22 10:00:00.003, DECLARE @p datetime2(7) = '2026-11-22 10:00:00.003'; SELECT COUNT(*) FROM ev WHERE at = @p; returned 0 at level 160 and 1 after ALTER DATABASE CURRENT SET COMPATIBILITY_LEVEL = 120. Microsoft lists this among the SQL Server 2016 breaking changes and advises an explicit cast wherever the two types meet. A driver that sends parameters as DATETIME2 against an unconverted DATETIME column hits exactly this. Converting to DATETIME2(3) fixes it, because the conversion rounds .0033333 back to .003 and the same query then returned 1. Converting to DATETIME2(7) does not: the column keeps .0033333, and the query still returned 0.

How much does the conversion cost on a large table?

On one million rows, each conversion took about 1.4 seconds and wrote 106 MB of transaction log, whatever precision it targeted.

The migration that works drops what blocks it, alters, and puts it back, with the default switched to SYSDATETIME() so new rows get more than 1/300 s:

DROP INDEX ix_orders_created_at ON orders;
ALTER TABLE orders DROP CONSTRAINT df_orders_created_at;
ALTER TABLE orders ALTER COLUMN created_at datetime2(3) NOT NULL;
ALTER TABLE orders ADD CONSTRAINT df_orders_created_at DEFAULT SYSDATETIME() FOR created_at;
CREATE INDEX ix_orders_created_at ON orders (created_at);

Measured from a restored copy each time, under the full recovery model:

Target ALTER COLUMN time Log written Bytes per value First row (.037) after conversion
DATETIME2(3) 1.41 s 106 MB 7 00:00:00.037
DATETIME2(7) 1.34 s 106 MB 8 00:00:00.0366667
DATETIME2(0) 1.36 s 106 MB 6 00:00:00

DATETIME2(7) is the same 8 bytes as DATETIME and still rewrote every row, because the two types store time in different formats. With the ALTER COLUMN inside an open BEGIN TRAN, a second session running SET LOCK_TIMEOUT 2000; SELECT TOP 1 id FROM orders WHERE id = 5 failed with Msg 1222: the first session held a schema modification (Sch-M) lock on the table. On Enterprise edition, adding WITH (ONLINE = ON) to the ALTER COLUMN is the alternative; Microsoft documents it as following the locking pattern of an online index build, which takes Sch-M only briefly at the end, and here it took 2.3 seconds instead of 1.4. The shortcut that makes SQL Server INT to BIGINT nearly free does not apply either: on a copy rebuilt with DATA_COMPRESSION = ROW, the same conversion still wrote 141 MB of log. Plan the conversion for a window, and on a table of hundreds of millions of rows, budget the log for it.

The DATETIME2(0) row is the trap. It ran without an error or a warning, and every value lost its milliseconds: the first order, stamped .037, became 00:00:00, and 10:00:29.500 rounds up to 10:00:30. Rounding is not truncation, so some rows even move into the next second, minute or day. Changing DATETIME to DATETIME2 with fewer than 3 fractional digits, to SMALLDATETIME or to DATE, or DATETIME2(3) and finer back to DATETIME, changes stored data, and going back to DATETIME also fails outright on any date before 1753.

Find the other casualties before the window. Search the code that touches the column for + and - with integers and for DATETIME variables compared against it, and run sys.dm_sql_referenced_entities on each procedure that reads the table. Then list what blocks the ALTER COLUMN besides the default and indexes: CHECK constraints, foreign keys, computed columns, statistics made with CREATE STATISTICS, and views created WITH SCHEMABINDING, which in our test failed it with the same Msg 5074.

How Schemity shows the cost before the conversion runs

Schemity reports every DATETIME and SMALLDATETIME column as a lint finding, and shows what changing one costs before any SQL runs.

Schemity is database design software that reads your live database, shows the impact of every schema change before it runs, and keeps the diagram as a file in Git. Connected to a SQL Server database, its schema lint marks each DATETIME column with the sqlserver-datetime-rounding finding: "DATETIME rounds to steps of 1/300 second, so 10:00:00.001 is stored as 10:00:00.000." A SMALLDATETIME column gets "SMALLDATETIME rounds to the minute." Both say DATETIME2 stores 100-nanosecond steps in 6 to 8 bytes. That turns a type nobody chose on purpose into a list you can work through, table by table.

Schemity lint drawer showing the sqlserver-datetime-rounding finding on orders.created_at, a DATETIME column

Changing the type in the field dialog does not touch the database. The planned migration drops the default and the index, runs ALTER COLUMN with NOT NULL restated, and creates both again as the diagram defines them; switch the default to SYSDATETIME() in the same edit and it is the sequence above, written for you. Impact analysis then lists the cost against the live row count: "Rewrites orders to change created_at", and "Changing the type of created_at holds back reads and writes to orders" and, for the index it recreates, "Building the index holds back writes to orders", each with the estimated rows and size on disk. A precision below 3, or a change back to DATETIME from 3 digits or more, adds "values may not survive the cast", and any change back to DATETIME adds "fails if a value does not fit" for dates before 1753, so the DATETIME2(0) mistake shows up as a finding instead of as missing milliseconds a week later. The same analysis reads a schema migration file an ORM or an AI agent wrote, and the migration SQL diff shows the exact statements before Migrate runs them. This is what "see the impact of every change" means for a type swap that looks like a rename.

Schemity Preview changes for created_at changed to DATETIME2(3): the planned migration drops the index and default, alters the column NOT NULL, recreates both, and impact analysis lists three findings on ~1M rows

Schemity Preview changes for created_at changed to DATETIME2(0): impact analysis adds the finding that values may not survive the cast on ~1M rows

Should you convert DATETIME columns to DATETIME2?

DATETIME2(3) is the right default for SQL Server timestamps, and converting an old DATETIME column is worth doing, but it is a table rewrite with a schema lock, not a metadata edit, and its precision decides whether stored values change.

The PostgreSQL counterpart of choosing between a clock reading and an instant is timestamp vs timestamptz, and SQL Server's other create-time refusal is multiple cascade paths, Msg 1785.

來源:DEV Community · dev.to