Reputation: 10755
if i put something
DECLARE @Query VARCHAR(8000)
SET @Query = 'select * from subscriber
where sbs_userid = ' + cast(@UserID as varchar) + '
and SBS_Status in (select statusFlag from #tmpStatusFlag)
and SBS_SourceFlag in (select sourceFlag from #tmpSourceFlag)'
IF (@FirstName !='')
SET @Query = @Query + ' and SBS_FirstName like ''%' + @FirstName + '%'''
IF(@LastName !='')
SET @Query = @Query + ' and SBS_LastName like ''%' + @LastName + '%'''
IF(@Phone !='')
SET @Query = @Query + ' and SBS_WorkPhone like ''%' + @Phone + '%'''
IF(@EmaiAdderess !='')
SET @Query = @Query + ' and SBS_EmailAddress like ''%' + @EmaiAdderess + '%'''
IF(@City !='')
SET @Query = @Query + ' and SBS_City like ''%' + @City + '%'''
IF(@SubListId !='-1')
SET @Query = @Query + ' and SBS_SubListId like ''%' + @SubListId + '%'''
SET @Query = @Query + ' order by SBS_CreationDate desc'
EXEC (@Query)
in my stored procedure .
my question is still i get the benefits of stored procedure or is it a wrong approach
i never use this but my Team Leader used this to speed up the stored proceure . is it ok ?
EDITED
IF we use sp_executesql instead of exec then we can take the benefits of stored procedure.and is this ok with this ?
Upvotes: 3
Views: 2765
Reputation: 453057
No.
You would need to use EXEC sp_executesql
to get the advantages of parameterisation (plan reuse - protection from SQL injection).
These leading wild card searches are going to be expensive anyway. Have you considered Full Text Indexing?
Following the edit
If we use
sp_executesql
instead ofexec
then we can take the benefits of stored procedure.and is this ok with this ?
Not all the benefits of stored procedures. A couple of advantages that stored procedures would still have over sp_executesql
would be that you could then use ownership chaining and only need to grant exec
permissions on the stored procedure rather than select
on the underlying objects. Additionally having static stored procedures rather than dynamic SQL strings can make it easier to find dependant objects when refactoring the database.
However in your case you would need 64 separate procedures for each combination of presence/absence for the 6 optional parameters and this number grows exponentially as more optional parameters are added.
See Dynamic Search Conditions in T-SQL Version for SQL 2005 and Earlier for a thorough discussion of this topic.
Upvotes: 4