noob.spt noob.spt - 1 year ago 87
SQL Question

Function call in where clause

I have a query as below:

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)

FROM Members (NOLOCK) WHERE Phone= @SomeVar

Which way is better or both are good?

EDIT: And how is first query different from

WHERE dbo.FormatPhone(Phone) = @Phone

Answer Source

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 NOLOCK is always the wrong answer. Use snapshot isolation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download