我正在创建一个存储过程,我需要使用之前设置的值。我很难解释这个,所以我将使用一个例子:
CASE
WHEN ((select top 1 stuksweergeven from componenten
where componentid = componentlink.componentid) = 1) and
((select opbrengstperkilo from componenten
where componentid = componentlink.componentid) <> 0) THEN
amount1 * (select opbrengstperkilo from componenten
where componentid = componentlink.componentid)
ELSE
amount1
END AS Total,
Amount1 * Total *(SELECT dbo.SelectReceptenLinkGewicht(Componentid,0)) AS TotalWeight
我做了一个CASE
,结果是Total。之后我想使用Total来计算TotalWeight。
抱歉我的英文。
答案 0 :(得分:5)
问题是SELECT
列表中的所有表达式都以all at once
方式进行评估。这就是您需要复制代码的原因。但您可以为此创建subquery
或cte
喜欢:
with cte as(
select Amount1,
ComponentID,
CASE
WHEN ((select top 1 stuksweergeven from componenten where componentid = componentlink.componentid) = 1) and ((select opbrengstperkilo from componenten where componentid = componentlink.componentid) <> 0)
THEN amount1 * (select opbrengstperkilo from componenten where componentid = componentlink.componentid)
ELSE amount1
END AS Total
from SomeTable)
select Total,
Amount1 * Total *(SELECT dbo.SelectReceptenLinkGewicht(Componentid,0)) AS TotalWeight
from cte
或者:
select Total,
Amount1 * Total *(SELECT dbo.SelectReceptenLinkGewicht(Componentid,0)) AS TotalWeight
from (
select Amount1,
ComponentID,
CASE
WHEN ((select top 1 stuksweergeven from componenten where componentid = componentlink.componentid) = 1) and ((select opbrengstperkilo from componenten where componentid = componentlink.componentid) <> 0)
THEN amount1 * (select opbrengstperkilo from componenten where componentid = componentlink.componentid)
ELSE amount1
END AS Total
from SomeTable) t
答案 1 :(得分:2)
您可以完全使用CROSS APPLY
让事情适合您。一篇内容丰富的文章:http://sqlmag.com/blog/tip-apply-and-reuse-column-aliases
答案 2 :(得分:1)
只需使用派生表,例如:
select col1, col2
from (select c1 * c2 + c3 as col1,
... as col2
from tablename)
where col1 = ...
答案 3 :(得分:0)
您可以使用交叉申请
SELECT
t.Amount1 * x.Total * dbo.SelectReceptenLinkGewicht(t.Componentid,0)
AS TotalWeight
FROM table t
CROSS APPLY
(
SELECT
CASE
WHEN ((SELECT top 1 stuksweergeven from componenten
WHERE componentid = componentlink.componentid) = 1) and
((SELECT opbrengstperkilo from componenten
WHERE componentid = componentlink.componentid) <> 0) THEN
amount1 * (select opbrengstperkilo from componenten
WHERE componentid = componentlink.componentid)
ELSE
amount1
END AS Total
) x