因此,我尝试将 Option Recompile 添加到内联 TVF 中,但似乎是不允许的。我发现的唯一方法是创建一个多语句函数,但它们有其缺点:
设置
CREATE Table MyTest
(
ID INT PRIMARY KEY Identity,
SomeValue VARCHAR(MAX),
UpdateDate Date
)
CREATE INDEX IDX_MyTest_UpdateDate
ON MyTest(UpdateDate)
GO
创建函数
CREATE FUNCTION MyFunction(@FromDate date, @ToDate Date)
RETURNS TABLE
AS
RETURN
(
SELECT SomeValue, UpdateDate
FROM MyTest
WHERE UpdateDate >= @FromDate AND
UpdateDate <=@ToDate
-- OPTION (RECOMPILE) **** NOT ALLOWED HERE**
)
GO
CREATE FUNCTION MyFunction2(@FromDate date, @ToDate Date)
RETURNS @retMyFunction TABLE
(
SomeValkue VARCHAR(MAX),
UpdateDate Date
)
AS
BEGIN
INSERT INTO @retMyFunction
SELECT SomeValue, UpdateDate
FROM MyTest
WHERE UpdateDate >= @FromDate AND
UpdateDate <=@ToDate
OPTION (RECOMPILE);
RETURN;
END
GO
加载数据
INSERT INTO MyTest (SomeValue, UpdateDate)
SELECT CAST(X.n * Y.n * z.n AS VARCHAR(Max)), DATEADD(D, ROW_NUMBER() OVER (ORDER BY X.n), '2010-01-01')
FROM (VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10)) X(n)
CROSS APPLY (VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10)) Y(n)
CROSS APPLY (VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10)) Z(n)
测试
-- Index Scan
SELECT * FROM MyTest
WHERE UpdateDate > '2010-01-02' AND UpdateDate < '2020-01-01'
-- Index Seek
SELECT * FROM MyTest
WHERE UpdateDate > '2010-01-02' AND UpdateDate < '2010-01-05'
-- Index Scan
SELECT *
FROM MyFunction('2010-01-02', '2020-01-01')
-- Index Scan
SELECT *
FROM MyFunction('2010-01-02', '2010-01-05')
-- Index Scan
SELECT *
FROM MyFunction2('2010-01-02', '2020-01-01')
-- Index Seek
SELECT *
FROM MyFunction2('2010-01-02', '2010-01-05')