如果包含功能的select语句如何重写?

时间:2018-10-09 10:55:54

标签: sql-server performance function optimization conditional-statements

经过全部优化,我发现存储该select语句要花费大量时间,因为它在select和where condition中包含函数。请帮助我重新编写select语句。

if OBJECT_ID('QATR_TestCase0003_ElementElIDContainsUpperCase')         
is not null drop table QATR_TestCase0003_ElementElIDContainsUpperCase        
select elid, tsmkey, dbo.[ContainCapLetter](elid) ContaintCap ,  
cast('Element elid  '+elid+' contains UPPER CASE in GenProductsAll ' as 
nvarchar(255)) datastatus         
into QATR_TestCase0003_ElementElIDContainsUpperCase from TblGenProductsAll        
where dbo.[ContainCapLetter](elid) <>0

下面是我写的函数:

CREATE FUNCTION [dbo].[ContainCapLetter] (@str1 as nvarchar(255))    
RETURNS int  
BEGIN   
declare @j int,  @i int
set @i=0  
 select @j = len(@str1)  

while @j >0  
begin  
If unicode(left(@str1,1)) not between 64 and 91  
begin  
set @str1 = right(@str1,len(@str1)-1)  
select @j= len(@str1)  
end  

Else If unicode(left(@str1,1)) between 64 and 91  
begin  
set @i= 1  
set @j= 0  
end  

end  
return @i  
END  

1 个答案:

答案 0 :(得分:1)

您可以尝试一下。

select elid, tsmkey, 
    CASE WHEN elid like '%[ABCDEFGHIJKLMNOPQRSTUVWXYZ]%' COLLATE Latin1_General_CS_AS THEN 1 ELSE 0 END ContaintCap ,
    cast('Element elid  '+elid+' contains UPPER CASE in GenProductsAll ' as nvarchar(255)) datastatus         
into QATR_TestCase0003_ElementElIDContainsUpperCase 
from TblGenProductsAll        
where 
    elid like '%[ABCDEFGHIJKLMNOPQRSTUVWXYZ]%' COLLATE Latin1_General_CS_AS