SQL Server 2008: Get date part from datetime2

Trent picture Trent · Dec 8, 2012 · Viewed 12.7k times · Source

I've been using this very handy method of extracting the date portion from a datetime value:

select dateadd(day, datediff(day, 0, @inDate), 0)

This basically zeroes out the time portion of the date. It's fast, and more importantly it's deterministic - you can use this expression in a persisted computed column, indexed view, etc.

However I'm struggling to come up with something that works with the datetime2 type. The problem being that SQL Server does not permission conversions from integers to the datetime2 type.

Is there an equivalent, deterministic method of stripping the time portion from a datetime2?

Answer

marc_s picture marc_s · Dec 8, 2012

Can't you just do a

ALTER TABLE dbo.YourTable
ADD DateOnly AS CAST(YourDate AS DATE) PERSISTED

The CAST(... AS DATE) turns your datetime2 column into a "date-only", and it seems to be deterministic enough to be used in a persisted, computed column definition ...