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 2000 Forums
 SQL Server Development (2000)
 Same query with variable takes long time

Author  Topic 

netzorro
Starting Member

6 Posts

Posted - 2013-02-04 : 13:54:36
Hi, just an update:

UPDATE [MP11PRD].[dbo].SA1010
SET A1_PESSOA = 'J', A1_TIPO = 'I', A1_LC = '500000',
A1_NREDUZ= 'XXX', A1_NROIB = '',
A1_NOME = 'XXX' where A1_XCLIANT = 91564

This update takes about 0 seconds

Now check this:

declare @A1_PESSOA varchar(1)
set @A1_PESSOA = 'J'
UPDATE [MP11PRD].[dbo].SA1010
SET A1_PESSOA = @A1_PESSOA, A1_TIPO = 'I', A1_LC = '500000',
A1_NREDUZ= 'XXX', A1_NROIB = '',
A1_NOME = 'XXX' where A1_XCLIANT = 91564

And this update exactly the same but just A1_PESSOA as a variable takes 15 seconds.
The Column A1_PESSOA is a varchar(1)

SQLServer2000 SP4
Any ideas?
Thanks,
Diego

TG
Master Smack Fu Yak Hacker

6065 Posts

Posted - 2013-02-04 : 14:23:53
If you compare the actual query plans between the two statements I'm sure you will see differences. That is reason for the difference in time. Now the reason that the plans are different is the question. It is much more common to see this issue when the parameter is used in the WHERE clause. Because your example has the parameter as the column value being updated I suspect that column is a foreign key or references a foreign key? Perhaps even participates in cascading actions? Some options to correct this include:

- force the use of an index or join by using a HINT. This is dangerous unless you know that every time this statement is called that forced plan is the correct one.

- turning the statement into a stored procedure can sometimes make a difference because of the techniques sql uses to cache plans.

- turning statement into a dynamically built statement that can then be EXEC'd with either EXEC or SP_EXECUTESQL will definitely solve this problem but raises other potential issues (like security, permissioning, and/or more complex code to maintain).

EDIT:
The reason sql may come up with the wrong plan when parameters are used is because at run time when the statement is parsed and devises a plan, the optimizer doesn't have the benefit of knowing the value of the parameter. Without values to work with it can't use the statistics to guarantee that an index will be beneficial. So it just decides to scan the entire table.

Be One with the Optimizer
TG
Go to Top of Page
   

- Advertisement -