如何修改为sargable-sql

时间:2015-10-18 10:30:28

标签: sql sql-server

我有以下查询

update r
   set Comp = t.Comp
from [QlikDataWarehouse].[dbo].[Vente]r
 inner join
     [QlikDataWarehouse].[dbo].[Budget] t
     on t.[Code Site] = r.[Code Site] and
        t.[Code Rayon] = substring(r.[Code Structure],1,4) and
        t.[Date Time] = convert(date,r.[Date Time])
where r.[Date Time] >= '2015-01-01 00:0:00.000';

预算行数约为800000,排放量约为350 +百万行。 我创建了索引vente([Date Time], [Code Site], [Code Structure])Budget([Code Site], [Code Rayon], Date Time])。但是这个查询花了好几天的时间。

t.[Code Rayon]是一种int类型 t.[Date Time]是日期类型 r.[Date Time]是日期时间类型 有没有办法制作条款On sargable?

任何帮助都是最受欢迎的。

1 个答案:

答案 0 :(得分:0)

如果您希望这是可以搜索的,则在其上添加计算列和索引。

. . . 
from [QlikDataWarehouse].[dbo].[Vente] r inner join
     [QlikDataWarehouse].[dbo].[Budget] t
     on t.[Code Site] = r.[Code Site] and
        t.[Code Rayon] = substring(r.[Code Structure],1,4) and
        t.[Date Time] = convert(date,r.[Date Time])
where r.[Date Time] >= '2015-01-01 00:0:00.000';

处理联接:

alter table Vente add code4 as (left([Code Structure], 4);
alter table Vente add datecol as cast([Date Time] as date);
create index idx_vente_4 on Vente([Code Site], code4, datecol, [Date Time];

将查询的这一部分写成:

from [QlikDataWarehouse].[dbo].[Vente] r inner join
     [QlikDataWarehouse].[dbo].[Budget] t
     on t.[Code Site] = r.[Code Site] and
        t.[Code Rayon] = code4 and
        t.[Date Time] = datecol
where r.[Date Time] >= '2015-01-01 00:0:00.000';

过滤join之前的数据:

alter table Vente add yyyy as (year([Date Time]) 
create index idx_vente_4 on Vente(yyyy, [Code Site], code4, datecol, [Date Time];

然后将此部分查询写为:

from [QlikDataWarehouse].[dbo].[Vente] r inner join
     [QlikDataWarehouse].[dbo].[Budget] t
     on t.[Code Site] = r.[Code Site] and
        t.[Code Rayon] = code4 and
        t.[Date Time] = datecol
where r.yyyy = 2015;