过滤索引:
CREATE NONCLUSTERED INDEX [FILTEREDIDX_MYTable_OID]
ON [dbo].[MYTable] (column3 ASC)
INCLUDE (column1, column2)
WHERE (column3 IN ((1), (2), (3)))
功能:
CREATE FUNCTION [dbo].[funcTest]
(@list as varchar(8000), @delim as varchar(10))
RETURNS @lTable table(Value INT)
AS
BEGIN
DECLARE @DelimP INT
SET @DelimP = CHARINDEX(@delim, @list)
WHILE @DelimP > 0
BEGIN
INSERT INTO @lTable(Value)
VALUES(CAST(RTRIM(LEFT(@list, @DelimP - 1)) AS INT))
SET @list = right(@list, len(@list) - @DelimP)
SET @DelimP = CHARINDEX(@delim, @list)
END
IF len(@list) > 0
INSERT INTO @lTable(Value)
VALUES(CAST(RTRIM(@list) AS INT))
RETURN
END
存储过程:
CREATE PROCEDURE [dbo].[sp_GetList]
@ParameterString varchar(8000)
AS
BEGIN
SET NOCOUNT ON;
SELECT column1, column2
FROM MYTable
WHERE column3 IN (SELECT Value
FROM funcTest(@ParameterString,','));
END
当我使用表值函数时,查询正常,但不会使用过滤后的索引。
我想在column3(int数据类型)中使用过滤器索引来减少逻辑读取。
如果我们只使用参数,将使用过滤后的索引。
Exec sp_GetList '1,2,3'
错误:SELECT column1,column2 FROM MYTable WHERE column3 IN (@ParameterString);
- 因为@ParameterString
是varchar
。
SELECT column1, column2
FROM MYTable
WHERE column3 IN ('1,2,3');
错误消息:将varchar值“1,3”转换为数据类型int时转换失败。
好的:
SELECT column1, column2
FROM MYTable
WHERE column3 IN (1,2,3);
我该如何解决这个问题?
答案 0 :(得分:0)
根据评论......
尝试将函数的结果加载到表变量中并加入到:
CREATE PROCEDURE [dbo].[sp_GetList]
@ParameterString varchar(8000)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @T Table (Value INT)
INSERT INTO @T(Value)
SELECT DISTINCT Value FROM funcTest(@ParameterString,',')
SELECT column1, column2
FROM MYTable
INNER JOIN @T T
ON T.Value = column3
END