I created a stored procedure.
Following are the requirements:
- First match is done on company name and person name.
- If match not found, second match should be done on address, city, and person name.
- If match not found, third match should be done on zip and person name.
What I wrote was
exec('insert into ProcessedFile_'+@fileuplodedId +' ('+@ConcatAppendedField+ ',UploadedB2bFiled_id) select '+@concatAppendFieldForSelect +',B2bFiled_id from UploadedFile_'+@fileuplodedId+' a , b2bdb b where ((a.CompanyDomain = b.domain and ISNULL(a.CompanyDomain,'''') <> '''' and a.CompanyDomain is not null and a.Name=b.Name)) group by B2bFiled_id,' + @concatAppendFieldForGroupBy )
exec('insert into ProcessedFile_'+@fileuplodedId +' ('+@ConcatAppendedField+ ',UploadedB2bFiled_id) select '+@concatAppendFieldForSelect +',B2bFiled_id from UploadedFile_'+@fileuplodedId+' a , b2bdb b where (((a.CompanyDomain is null or a.CompanyDomain !=b.domain) and a.Address1 = b.address and a.City = b.city and a.Name = b.Name )) group by B2bFiled_id,' + @concatAppendFieldForGroupBy)
exec('insert into ProcessedFile_'+@fileuplodedId +' ('+@ConcatAppendedField+ ',UploadedB2bFiled_id) select '+@concatAppendFieldForSelect +',B2bFiled_id from UploadedFile_'+@fileuplodedId+' a , b2bdb b where ((((a.CompanyDomain is null or a.CompanyDomain !=b.domain) and (a.Address1 = b.address and a.City = b.city and a.Name = b.Name )) and a.Zip = b.Zip and a.Name = b.Name )) group by B2bFiled_id,' + @concatAppendFieldForGroupBy)`
But this is absolutely inefficient as,at each statement(except the first one) I am comparing all the fields I did before as in first I compared company name and person name and in second statement I am comparing again those fields(company name and person name).
How to get rid of this?
You could add a
RETURNstatement after each insert to exit the batch if rows are inserted. This way you don’t have to eliminate the criteria from the previous query. e.g.I have copied your clauses but it is worth pointing out that the following where clause can be simplified.
Since NULL does not equal anything, not even NULL, if a.CompanyDomain IS NULL then it can never equal b.Domain, so this can be simplified to
ADENDUM
Okay, as I now understand it you don’t want to abort execution if the first query returns results, you just want to exclude anything inserted by the first query from the second, and anything inserted by the first and second from the 3rd so you avoid duplicates from being inserted? If that is the case I think you can get around this by combining all the criteria into one query:
If this isn’t what is required I think you may have to use your original solution of 3 inserts as it sounds like you are using data inserted by the first query in the second, and data inserted in the first and second in the third.