Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
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: Tuesday, September 22, 2015 8:55 AM
Points: 128, Visits: 1,143
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: Today @ 9:07 AM
Points: 43,025, Visits: 40,004
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
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