Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 How best to handle this

Author  Topic 

eglons
Starting Member

15 Posts

Posted - 2013-06-04 : 18:09:36
OK novice stored proc writer here, learned mostly from Google. I'm having a lot of problems with recompilation of a stored procedure slowing it down. I've used dynamic SQL to build the query and execute to run it and I think this may be the issue. Here's a piece of what I'm trying to do

SELECT @SearchSQL =
' insert into #admin_stats ' +
' SELECT ''client_tickets'', count(*), ''nct'', ''n'', '''', '''' ' +
' FROM Ticket ' +
' WHERE ticket_status = 10 '

IF @admin<>''
SELECT @SearchSQL = @SearchSQL + ' AND ticket_assigned_to=''' + @admin + ''''

EXECUTE(@SearchSQL)

<lots of similar blocks like this then...>

select * from #admin_stats OPTION (KEEPFIXED PLAN);


It seems to take an age to run first time, then is very quick if run a few times quickly after that... leave it for a while and it's back to being slow hence my theory about recomplile... you can see I've added OPTION (KEEPFIXED PLAN) to try and force no recompile but no difference as far as I can tell...

Any ideas on making this work without recompiling OR how to write it a little more correctly?

It's being called from an asp webpage if that's relevant

Transact Charlie
Master Smack Fu Yak Hacker

3451 Posts

Posted - 2013-06-04 : 19:21:07
use sp_execute SQL with parameterised queries. at the moment each different value for @admin is causing a new compilation of the code. With parameterised calls you'll get one compiled plan for each permutation of variables rather than values.

Read this : http://www.sommarskog.se/dynamic_sql.html


Transact Charlie
Msg 3903.. The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION.
http://nosqlsolution.blogspot.co.uk/
Go to Top of Page

Transact Charlie
Master Smack Fu Yak Hacker

3451 Posts

Posted - 2013-06-04 : 19:23:02
Also:

http://sqlinthewild.co.za/index.php/2009/03/19/catch-all-queries/

Transact Charlie
Msg 3903.. The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION.
http://nosqlsolution.blogspot.co.uk/
Go to Top of Page
   

- Advertisement -