2017-07-18 102 views
-2

我已經使用replace來清理字段。但需要執行時間。這個查詢需要很多時間來執行,如何優化它?

select c.* 
from 
( 
select distinct a.*, b.* 
from 
( 
--Table 1 
select replace(replace(replace(replace(AGENCY_NAME,'',''),'',''),'/',''),'\\','') 
as agency_name,  
LEN(replace(replace(replace(replace(AGENCY_NAME,' ',''),'-',''),'/',''),'\\',''))  
as agency_len 
from dbo.tbl_stars_agency 
where replace(replace(replace(replace(AGENCY_NAME,' ',''),'-',''),'/',''),'\\','') 
not in ('') 
) a  
inner join 
( 
--Table 2 
select replace(replace(replace(replace(RESPONDENT_NAME_PER,' ',''),'.',''),'/',''),'\\','') 
as respondent_name, 
len(replace(replace(replace(replace(RESPONDENT_NAME_PER,' ',''),'-',''),'/',''),'\\','')) 
as respondent_len 
from dbo.TBL_cacs_ecb 
where replace(replace(replace(replace(RESPONDENT_NAME_PER,' ',''),'-',''),'/',''),'\\','') not in ('')  
) b 
on substring(a.agency_name,1,15)=SUBSTRING(b.respondent_name,1,15) 
) c 
inner join 
( 
--Table 3 
select replace(replace(replace(replace(NM_ENTITY,' ',''),'-',''),'/',''),'\\','') 
as nm_entity, 
LEN(replace(replace(replace(replace(NM_ENTITY,' ',''),'-',''),'/',''),'\\','')) 
as nm_entity_len 
from dbo.RMFS010_TF1NAME 
where replace(replace(replace(replace(NM_ENTITY,' ',''),'-',''),'/',''),'\\','') 
not in ('') 
) d 
on substring(c.agency_name,1,5)=substring(d.nm_entity,1,5) or 
substring(c.respondent_name,1,5)=substring(d.nm_entity,1,5) 

我想根據表中的名稱字段比較三個表。我計算了長度和使用子字符串函數以匹配15個位置。

+2

請google重新編寫stackoverflow問題標記,然後使用代碼塊格式(點擊「{}」)並查看您的帖子如何顯示在編輯窗口下方。另請閱讀[問]和[mcve]。還閱讀關於DBMS和用戶查詢優化。 – philipxy

+0

請格式化您的代碼。乍一看,因爲您正在進行數據清理,所以在這種情況下添加索引可能無濟於事。 –

+0

希望現在它更容易理解。 – nfs

回答

0

一種方法是添加計算的列和索引他們:

ALTER TABLE dbo.tbl_stars_agency 
ADD agency_len AS LEN(replace(replace(replace(
replace(AGENCY_NAME,' ',''),'-',''),'/',''),'\','')) 
PERSISTED; 

現在添加一個索引:

CREATE INDEX MyIndex dbo.tbl_stars_agency 
(agency_len); 

現在,在這個任何搜索要快很多。

你可以改變這一行:

where replace(replace(replace(
replace(AGENCY_NAME,' ',''),'-',''),'/',''),'\','') 
not in ('') 

這樣:

where agency_len = 0 

試一下,如果它可以幫助我們可以看看這樣做是爲了其他列

PS:您需要要確定你的表情是水密的,並且不會由於長度無效等而崩潰,否則它會阻止你插入和更新記錄

相關問題