Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2008: Get date part from datetime2

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?

like image 481
Trent Avatar asked Dec 08 '12 11:12

Trent


1 Answers

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 ...

like image 192
marc_s Avatar answered Oct 06 '22 01:10

marc_s