Here is my SQL query in SQL Server 2008.
Three identical queries, with different approaches
Declare @UploadDetailID nvarchar(500) = '62703,62709,67161,67167,74580,76728,76774,76777,89001,116048,602337,52674,626855,626863,626877,626862,626874,626861,626873,626857,626860,626872,636929,636938, 636925,636937,636924,636920,636922,636934,636923,644566,644574,644565,644577,644564,644563,644561,646566,646578,646567,646575,646565,646562,646564,653093,653096,653103';
Begin
select top 500 *
from SignatureDetail
where (Case When @UploadDetailID = '' then 1
When ','+@UploadDetailID+',' like '%,' + ltrim(UploadDetailID) + ',%' then 1
Else 0
End) = 1
select top 500 *
from SignatureDetail
where ',' + @UploadDetailID + ',' like '%,' + ltrim(UploadDetailID) + ',%'
select top 500 *
from SignatureDetail
where (Case when ',' + @UploadDetailID + ',' like '%,' + ltrim(UploadDetailID) + ',%' then 1 else 0 End) = 1
End
Here are the query costs:
(1) First query with Case
and two When
conditions is taking only 4% of query cost
select top 500* from SignatureDetail where
(Case when @UploadDetailID='' then 1
When ','+@UploadDetailID+',' like '%,'+ltrim(UploadDetailID)+',%' then 1
else 0 End)=1
(2) Second query without Case
condition is taking 48% of the total query cost
select top 500* from SignatureDetail where ','+@UploadDetailID+',' like '%,'+ltrim(UploadDetailID)+',%'
(3) Third query with Case
and one When
condition is also taking 48% of the total query costs
select top 500* from SignatureDetail where (Case when ','+@UploadDetailID+',' like '%,'+ltrim(UploadDetailID)+',%' then 1 Else 0 End)=1
Why do the second and third query take up so much of the total query costs?