sql - How to structure a query with a large, complex where clause? -
sql - How to structure a query with a large, complex where clause? -
i have sql query takes these parameters:
@searchfor nvarchar(200) = null ,@searchinlat decimal(18,15) = null ,@searchinlng decimal(18,15) = null ,@searchactivity int = null ,@searchoffers bit = null ,@startrow int ,@endrow int the variables @searchfor, @searchactivity, @searchoffers can either null or not null. @searchinlat , @searchinlng must both null, or both have values.
i'm not going post whole query boring , hard read, clause shaped this:
( -- filter activity -- (@searchactivity null) or (@searchactivity = activities.activityid) ) , ( -- filter location -- (@searchinlat null , @searchinlng null) or ( ... ) ) , ( -- filter activity -- @searchactivity null or ( ... ) ) , ( -- filter has offers -- @searchoffers null or ( ... ) ) , ( ... -- more stuff ) i have read bad way construction query - sqlserver has problem working out efficient execution plan lots of clauses this, i'm looking other ways it.
i see 2 ways of doing this:
construct query string in client application,where clause contains filters relevant parameters. problem means not accessing database through stored procedures, else @ moment. change stored procedure examines arguments null, , executes kid procedures depending on arguments passed. problem here mean repeating myself lot in definition of procs, , harder maintain. what should do? or should maintain on doing? have option (recompile) set procedures, i've heard doesn't work right in server 2005. also, plan add together more parameters proc, want create sure whatever solution have scaleable.
the reply utilize dynamicsql (be in client, or in sp using sp_executesql), reason why long, here's link...
dynamic search conditions in t-sql
a short version one-size not fit all. , optimiser creates 1 plan 1 query, it's slow. solution go on using parameterised queries (for execution plan caching), have many queries, different types of search can happen.
sql sql-server sql-server-2005
Comments
Post a Comment