SQL:如何在单个查询中避免多个函数调用?

时间:2012-06-29 05:30:12

标签: sql sql-server-2008

我有一个接受标量值函数2次的查询,在选择列表中的字段中的一个位置,以及在连接条件中的第二个位置。我的问题是如何在单个查询中避免该函数调用? 感谢。

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

2 个答案:

答案 0 :(得分:2)

使用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

或子查询

select
    id,
    field1,
    field2,
    calculated
from
(
    select 
        field1,
        field2,
        calculated = myFunction(field1, field2)
    from
        table1
) t
where
    calculated = @someCondition

答案 1 :(得分: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'