优化非索引视图的选择查询

时间:2015-04-15 11:03:36

标签: sql-server sql-server-2008 tsql

我想通过ID从非索引视图中选择行。 这是视图定义:

CREATE VIEW [dbo].[_V_V3] 
AS 
SELECT (CONVERT(varchar,T1.PK_ID)+','+CONVERT(varchar,T2.PK_ID)) as ID,
T1.[Id] as [T1_Id],
T1.[V1] as [T1_V1],
T2.[Id] as [T2_Id],
T2.[V1] as [T2_V1] 
FROM [T1]  INNER JOIN [T2] ON (T2.V1=T1.V1)

其中T2.V1,T1.V1 - nvarchar。

我的选择查询:

SELECT * FROM [dbo].[_V_V3] WHERE ID IN ('1,1', '2,3', ....)

效果非常慢。使用1000个ID,此查询可能会执行几分钟。

有没有办法优化这个选择?

1 个答案:

答案 0 :(得分:1)

你能做到这一点:

查看

CREATE VIEW [dbo].[_V_V3] 
AS
T1.PK_ID as PK_ID1,
T2.PK_ID as PK_ID2,
T1.[Id] as [T1_Id],
T1.[V1] as [T1_V1],
T2.[Id] as [T2_Id],
T2.[V1] as [T2_V1] 
FROM [T1]  INNER JOIN [T2] ON (T2.V1=T1.V1)

<强>查询

SELECT * FROM [dbo].[_V_V3] 
WHERE
    ( 
        PK_ID1=1 AND PK_ID2=1
    )
    OR
    (
        PK_ID1=2 AND PK_ID2=3
    )

我认为整数比较比varchar比较快