创建索引视图

时间:2010-11-17 04:05:04

标签: sql sql-server tsql indexed-view

当我尝试创建索引视图时,我收到错误“datepart返回不确定值,使用系统定义的确定性函数或使用户定义的函数返回确定性值”当我尝试在视图上创建索引时出现此错误..

查询

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)`

在此date_time中是varchar(30)类型。给我一个解决方案,以解决这个问题。

1 个答案:

答案 0 :(得分:1)

使用:

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

问题是使用GETDATE();它是非确定性的,每次都返回不同的值。

所以你必须使用:

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