我正在尝试使用以下代码创建索引 View (这样我就可以将其发布到复制表中):
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
) 的表格,按第 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() 以使其具有确定性(在剥离时间时似乎应该如此)。如果没有人知道执行此操作的方法,我将关闭此问题并将创建日历表的建议标记为正确。
最佳答案
确定性函数的定义(来自 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.
请注意,此定义不涉及结果必须保持不变的任何特定时间跨度。对于给定的输入,它必须始终是相同的结果。
您可以想象的任何函数总是返回函数被调用时的日期,根据定义,如果您今天运行它并在第二天再次运行它,将返回不同的结果(无论数据库的状态)。
因此,返回当前日期的函数不可能是确定性的。
对这个问题的唯一可能的解释是,如果你愿意将一些关于今天是哪一天的信息作为输入传递给函数,那么唯一可能的解释就是确定性函数。
类似于:
select fn_myDeterministicGetDate('2015-11-25')
但我认为,就您而言,这会打败重点。
关于tsql - 获取今天日期的确定性函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33883877/