开发者

Creating indexed views

开发者 https://www.devze.com 2023-01-25 05:43 出处:网络
When I try to create indexed view I am getting an error \"datepart returns indeterministic value, use system defined deterministic function or make the user defined function to return determ开发者_JS百

When I try to create indexed view I am getting an error "datepart returns indeterministic value, use system defined deterministic function or make the user defined function to return determ开发者_JS百科inistic value" I get this error when i try to create index on the view..

The query is

CREATE VIEW dbo.two_weeks_performance WITH SCHEMABINDING
as 
  SELECT dbo.day_dim.date_time AS Date, dbo.order_dim.quantity AS Target_Acheived
    FROM dbo.day_dim 
    JOIN dbo.order_fact ON dbo.day_dim.day_id = dbo.order_fact.day_id 
    JOIN dbo.branch_dim ON dbo.order_fact.branch_id = dbo.branch_dim.branch_id 
    JOIN dbo.order_dim ON dbo.order_fact.order_id = dbo.order_dim.order_id
   WHERE (DATEPART(wk, CONVERT(datetime, dbo.day_dim.date_time, 101)) <= DATEPART(wk, GETDATE() - 2))
GROUP BY dbo.order_dim.quantity, dbo.day_dim.date_time
GO
CREATE UNIQUE CLUSTERED INDEX two_weeks_performance_I on two_weeks_performance (Date,Target_Acheived)`

In this date_time is varchar(30) type. Give me a solution to over come this problem.


Use:

CREATE VIEW dbo.two_weeks_performance WITH SCHEMABINDING
AS 
  SELECT dbo.day_dim.date_time AS Date, 
         dbo.order_dim.quantity AS Target_Acheived
    FROM dbo.day_dim 
    JOIN dbo.order_fact ON dbo.day_dim.day_id = dbo.order_fact.day_id 
    JOIN dbo.branch_dim ON dbo.order_fact.branch_id = dbo.branch_dim.branch_id 
    JOIN dbo.order_dim ON dbo.order_fact.order_id = dbo.order_dim.order_id   
GROUP BY dbo.order_dim.quantity, dbo.day_dim.date_time

The issue was the use of GETDATE(); it's non-deterministic, returning a different value every time.

So you'd have to use:

SELECT t.*
  FROM dbo.two_weeks_performance t
 WHERE DATEPART(wk, CONVERT(datetime, t.date, 101)) <= DATEPART(wk, GETDATE() - 2)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号