Function call in where clause

我的未来我决定 提交于 2019-12-12 10:38:14

问题


I have a query as below:

SELECT * FROM Members (NOLOCK) 
 WHERE Phone= dbo.FormatPhone(@Phone)

Now here I understand that formatting has to be applied on the variable on column. But should I apply it on variable to assign to some other local variable then use it (as below).

Set @SomeVar = dbo.FormatPhone(@Phone) 

SELECT * 
  FROM Members (NOLOCK) WHERE Phone= @SomeVar

Which way is better or both are good?

EDIT: And how is first query different from

SELECT * FROM Members (NOLOCK) 
 WHERE dbo.FormatPhone(Phone) = @Phone

回答1:


As usual with SQL, the query is largely irelevant without knowing the actual schema is used against.

Do you have an index on Members.Phone? If no, then it makes no difference how you write the query, they all gonna scan the whole table and performe the same (ie. perform badly). If you do have an index then the way you write the query makes all the difference:

SELECT * FROM Members WHERE Phone= @Phone;
SELECT * FROM Members WHERE Phone= dbo.FormatPhone(@Phone);
SELECT * FROM Members WHERE  dbo.FormatPhone(Phone)=@Phone;

First query is guaranteed optimal, will seek the phone on the index.
Second query depends on the characteristics of the dbo.FormatPhone. It may or may not use an optimal seek.
Last query is guaranteed to be bad. Will scan the table.

Also, I removed the NOLOCK hint, it seem the theme of the day... See syntax for nolock in sql. NOLOCK is always the wrong answer. Use snapshot isolation.




回答2:


You'll almost certainly get better predictability if you assign to a variable first, lots of dependency in the optimizer around determinism vs. non-determinism.




回答3:


The second is definitely preferred. The first one will evaluate the function for each row in the table, whilst the other one will do the calculation only once.




回答4:


SELECT * FROM Members (NOLOCK) 
WHERE Phone= dbo.FormatPhone(@Phone)

in the query above, function dbo.FormatPhone will be executed for every row in Members table.

when second query

Set @SomeVar = dbo.FormatPhone(@Phone) 

SELECT * 
FROM Members (NOLOCK) WHERE Phone= @SomeVar

it'll execute the function only once. So I think second option will be faster in case you have large data in member table.



来源:https://stackoverflow.com/questions/1724325/function-call-in-where-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!