SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 Same query with variable takes long time
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

netzorro
Starting Member

6 Posts

Posted - 02/04/2013 :  13:54:36  Show Profile  Reply with Quote
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
Flowing Fount of Yak Knowledge

USA
6062 Posts

Posted - 02/04/2013 :  14:23:53  Show Profile  Reply with Quote
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

Edited by - TG on 02/04/2013 14:34:11
Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.06 seconds. Powered By: Snitz Forums 2000