JsCoder
JsCoder

Reputation: 1733

Reuse field values in WHERE clause

How do I optimize the performance of the following T-SQL so heavyFunctionCall function will get called just once.

Looking for the fastest option among table variables, temp tables, CTEsor something else?

SQL:

select dbo.heavyFunctionCall(a, b, c) 
from T 
where dbo.heavyFunctionCall(a, b, c) > 10

Upvotes: 2

Views: 64

Answers (3)

A  ツ
A ツ

Reputation: 1267

maybe this:

select hFC.result
from T 
cross apply ( select dbo.heavyFunctionCall(T.a, T.b, T.c) result ) hFC
where hFC.result > 10

Upvotes: 1

Dudi Konfino
Dudi Konfino

Reputation: 1136

declare proc tst (@x int)  -- set @x whatever you want.
                           -- the execution plan will be the same.
as 
begin
SELECT * 
FROM (
  SELECT dbo.heavyFunctionCall(a, b, c) AS result
  FROM T) resultx
WHERE result > @x
end

Upvotes: 1

Dave Sexton
Dave Sexton

Reputation: 11188

Doing this would only run your function once on every row instead of twice:

SELECT * 
FROM (
  SELECT dbo.heavyFunctionCall(a, b, c) AS x
  FROM T) a
WHERE x > 10

Upvotes: 3

Related Questions