4

我一直在研究一个使用大量视图的数据库,并且表记录最多只有 100 万行,但是等待我的查询出现是一件很痛苦的事情。

我想复制视图并在里面放一个“WHERE CLAUSE”。现在我的问题:

将 where 子句放在视图中是否更快。例如,我会将所有客户类型 = 'BIZ'。

或者如果我只使用视图“SELECT * FROM VIEW_CUSTOMER WHERE type = 'BIZ'”会不会一样

4

3 回答 3

1

在此脚本的帮助下,可以使用您的 where 子句创建视图

DECLARE @pref nvarchar(10) = '_type$biz',
        @where_clause nvarchar(max) = 'WHERE 1 = 1',
        @dsql nvarchar(max) = ''
IF OBJECT_ID('tempdb.dbo.#tmp') IS NOT NULL DROP TABLE dbo.#tmp 
SELECT ROW_NUMBER() OVER(ORDER BY (SELECT 1)) AS rn,
       'CREATE VIEW ' + SCHEMA_NAME(o.schema_id) + '.' + OBJECT_NAME(o.object_id) + @pref
       + ' AS SELECT * FROM ' + SCHEMA_NAME(o.schema_id) + '.' + OBJECT_NAME(o.object_id) + ' ' + @where_clause AS def
INTO dbo.#tmp       
FROM sys.sql_modules m JOIN sys.objects o ON m.object_id = o.object_id
WHERE o.type = 'V'

DECLARE @i int = (SELECT MIN(rn) FROM dbo.#tmp)

WHILE (@i IS NOT NULL)
BEGIN
  SELECT @dsql = def FROM dbo.#tmp WHERE rn = @i
  EXEC sp_executesql @dsql
  SELECT @i = MIN(rn) FROM dbo.#tmp WHERE rn > @i
END
于 2012-11-14T09:55:45.233 回答
0

当您向视图添加 where 子句时,这将减少您选择的行数。默认情况下,调用视图时 sqlserver 不使用索引!要强制 sqlserver 使用可用索引,请在创建视图时指定“with schemabinding”(使用 schemabinding 创建视图...)。

一定要指定一个可以被 where 规范使用的索引。

于 2019-08-28T13:13:50.407 回答
-2

Adding another view with your filter will not help your performance. You should bring your concerns to your DBA. If you don't have a DBA... then you'll have to find a knowledgeable developer to help troubleshoot your query performance.

于 2012-11-14T04:03:21.237 回答