Click here to monitor SSC
SQLServerCentral is supported by Redgate
Log in  ::  Register  ::  Not logged in
Home       Members    Calendar    Who's On

Add to briefcase

Slow execution in dynamic SQL with OR clause Expand / Collapse
Posted Wednesday, October 16, 2013 3:57 AM


Group: General Forum Members
Last Login: Thursday, August 18, 2016 6:55 AM
Points: 131, Visits: 1,200
I have a stored procedure which accepts parameters and then builds the query and WHERE clause dynamically based on these parameters.
The performance is fine but now I have added another LEFT JOIN to a third table - the LEFT JOIN does not decrease performance - what does decrease performance is the added
OR clause on this table.

For example:
This section is fast:
SET @SQLWhere = @SQLWhere + ' OR (Table1.Col1 =' + QUOTENAME(@Value,'''') + ')'

But extending it like this makes it really slow:
SET @SQLWhere = @SQLWhere + ' OR (Table1.Col1 = '+ QUOTENAME(@Value,'''') + ' OR Table2.Col1 = '+ QUOTENAME(@Value,'''')+')'

The added OR section to Table2.Col1 slows this down from 4 seconds to over a minute.....

any ideas on how I can improve this?
Post #1505127
Posted Wednesday, October 16, 2013 4:34 AM



Group: General Forum Members
Last Login: Saturday, December 3, 2016 5:18 AM
Points: 45,619, Visits: 44,147
Probably missing indexes. OR requires different indexes to AND, without the query executes as a scan usually.

Gail Shaw
Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability

We walk in the dark places no others will enter
We stand on the bridge and no one may pass

Post #1505133
« Prev Topic | Next Topic »

Add to briefcase

Permissions Expand / Collapse