0

I have a query that accept the scalar-valued function 2 times, at one place in the field within the select list and second in the join condition. My question is that how to avoid that function call within single query? Thanks.

SELECT   i.Id, i.Name, . . . . . dbo.IsItemCApproved(C.Id) AS [Status], . . 
FROM @Item i 
JOIN Card C ON C.ItemId = i.Id 
AND C.Deadline IS NOT NULL 
AND dbo.IsItemCApproved(C.Id) = 'False' 
AND C.IsDeleted = 0
4
  • 1
    Q: Example SQL please? Q: What makes you think calling a function two times in the same query is necessarily a Bad Thing? If that's what the statement needs, and it results in one and only one call to the server, then it's the optimal thing to do! Commented Jun 29, 2012 at 5:32
  • Low quality, please provide an example Commented Jun 29, 2012 at 5:33
  • SELECT i.Id, i.Name, . . . . . dbo.IsItemCApproved(C.Id) AS [Status], . . FROM @Item i JOIN Card C ON C.ItemId = i.Id AND C.Deadline IS NOT NULL AND dbo.IsItemCApproved(C.Id) = 'False' AND C.IsDeleted = 0 Commented Jun 29, 2012 at 5:51
  • You can edit your question. And format code in questions (using {}). Asif has already suggested an edit, you should just need to approve it. Commented Jun 29, 2012 at 6:07

2 Answers 2

2

Using a CTE

with cte 
as 
(
    select
        id,
        calculated = myFunction(field1, field2)
    from
        table1
)
select
    id,
    field1,
    field2,
    calculated
from
    table1
inner join
    cte on cte.id = table1.id
where 
    cte.calculated = @someCondition

Or Sub querying

select
    id,
    field1,
    field2,
    calculated
from
(
    select 
        field1,
        field2,
        calculated = myFunction(field1, field2)
    from
        table1
) t
where
    calculated = @someCondition
Sign up to request clarification or add additional context in comments.

Comments

1
Select * from
(
SELECT   i.Id, i.Name, . . . . . dbo.IsItemCApproved(C.Id) AS [Status], . . 
FROM @Item i 
JOIN Card C ON C.ItemId = i.Id 
AND C.Deadline IS NOT NULL 
AND C.IsDeleted = 0
)A
WHERE [Status] = 'False'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.