Question

I want to create indexed view with such t-sql:

    Select
   Table1_ID,
   cast(CONVERT(varchar(8),
   t2.Object_CreationDate, 112)AS DateTime) as Object_CreationDate ,
   Count_BIG(*) as ObjectTotalCount 
   from
       [dbo].Table2 t2 inner join [dbo].Table1 t1 on ...   
   Group BY
       Table1_ID, CONVERT(varchar(8), t2.Object_CreationDate, 112))

I need to make group by only by datepart of column Object_CreationDate (type datetime2 ).

Also I want to set index on columns Theme_Id AND Object_CreationDate in the derived view.
If I use cast(CONVERT(varchar(8), m.Mention_CreationDate, 112)AS DateTime) in SELECT - I'll get problems with index on this column. Because this column (Object_CreationDate) is not deterministic.

I wonder if it is possible to solve a problem.

Was it helpful?

Solution

replace ...

CONVERT(varchar(8), t2.Object_CreationDate, 112))

... with

DATEADD(day, DATEDIFF(day, 0, t2.Object_CreationDate), 0)
--OR
CAST(t2.Object_CreationDate AS date)

The 2nd format is SQL Server 2008+ only, the 1st is more general

This removes the time component from a datetime value in the date/datetime datatype domain without any intermediate locale dependent datetime formats

See these answers: One and Two(comments)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top