获取今天日期的确定性函数

Deterministic function for getting today's date

我正在尝试使用以下代码创建索引视图(以便我可以将其发布为 table 进行复制):

CREATE VIEW lc.vw_dates
WITH SCHEMABINDING
AS

SELECT DATEADD(day, DATEDIFF(day, 0, GETDATE()), number) AS SettingDate
FROM lc.numbers
WHERE number<8

GO

CREATE UNIQUE CLUSTERED INDEX
idx_LCDates ON lc.vw_dates(SettingDate)

lc.numbers 只是具有 1 列 (number) 的 table,按第 1-100 行递增。

但是,我一直收到错误消息:

Column 'SettingDate' in view 'lc.vw_dates' cannot be used in an index or statistics or as a partition key because it is non-deterministic.

我意识到 GETDATE() 是不确定的。但是,有没有办法让它发挥作用?

我正在使用 MS SQL 2012.

编辑:希望能够转换 GetDate() 以使其具有确定性(在剥离时间时似乎应该如此)。如果没有人知道执行此操作的方法,我将关闭此问题并将创建日历 table 的建议标记为正确。

确定性函数的定义(来自MSDN)是:

Deterministic functions always return the same result any time they are called with a specific set of input values and given the same state of the database. Nondeterministic functions may return different results each time they are called with a specific set of input values even if the database state that they access remains the same.

请注意,此定义不涉及结果必须保持不变的任何特定时间跨度。对于给定的输入,它必须是相同的结果 总是

您可以想象的任何函数总是 return 在调用函数时 日期 ,根据定义,return 会得到不同的结果如果你 运行 有一天它然后第二天又一次(不管数据库的状态如何)。

因此,return当前日期的函数不可能是确定性的。

对这个问题的唯一可能的解释是,如果你愿意将一些关于今天是星期几的信息作为输入传递给函数,就可以启用确定性函数。

类似于:

select fn_myDeterministicGetDate('2015-11-25')

但我认为,就您而言,这会打败重点。