Friday, November 19, 2010

Dynamic SQL Query

Dynamic Sql query means genrating sql query at run time according to need. Some times a situation comes where we have to genrate the dynamic query. Below is the example of a search condition in stored procedure, where I am genrating dynamic query, according to parameter passed in Stored Procedure.
It has demerits too. It will loose the performance boost, what we usually get in stored procedures and most importantly stored procedure can not cache the execution plan for this dynamic query.


Stored Procedure
CREATE proc usp_Getsearchresult  
@countryid int,  
@cityid int,  
@categoryid int,  
@keywords varchar(255)  
as  
--TO HOLD THE QUERY
Declare @setQuery nvarchar(2200)      
--TO HOLD THE WHERE CONDITION VALUES
declare @whereTosearch nvarchar (2000)      
--TO HOLD THE CONDITION
declare @condition int      
set @setQuery='select * from product with (NOLOCK) where '  
 --Condition for country ID  . WHERE COUNTRY ID IS MANDATORY IN CODE
  if (@countryid is not Null)      
 begin      
   set @condition=1      
   set @whereTosearch='countryId='+cast(@countryid as varchar(5))      
 --print '1'  
 end     
 -- Condition for city   
  if (@cityid is not Null and @condition>0)      
 begin      
   set @condition=1      
   set @whereTosearch=@whereTosearch+' and cityId='+ cast(@cityid as varchar(5))  
 --print '2'  
 end     
 --Condition if catetory is selected  
  if (@categoryid is not Null and @condition>0)      
 begin      
   set @condition=1    
   set @setQuery='select product.*,product_category.product_category_type_id from product with (NOLOCK)  
   left  outer join product_category on  product.service_id=product_category.service_id where product_category.product_category_type_id is not null and '  
   set @whereTosearch=@whereTosearch+' and product_category.product_category_type_id='+cast(@categoryid as varchar(5))  
 --print '3'  
 end     
 -- Condition for Keywords   
  if (@keywords is not Null and @condition>0)      
 begin      
   set @condition=1      
   set @whereTosearch=@whereTosearch+' and (productname like ''%'+@keywords+'%'' or product_keyword like ''%'+@keywords+'%'')'  
 --print '4'  
 end   
  
set @setQuery=@setQuery+@whereTosearch      
--print @setQuery  
exec(@setQuery) 

1 comment: