Sql 稍后在查询中使用“AS ColumnName”的值
我正在创建一个存储过程,需要使用前面设置的值。我很难解释这一点,因此我将举一个例子:Sql 稍后在查询中使用“AS ColumnName”的值,sql,sql-server,stored-procedures,Sql,Sql Server,Stored Procedures,我正在创建一个存储过程,需要使用前面设置的值。我很难解释这一点,因此我将举一个例子: CASE WHEN ((select top 1 stuksweergeven from componenten where componentid = componentlink.componentid) = 1) and ((select opbrengstperkilo from componenten where com
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
我提出了一个案例,给出了总体结果。然后我想用Total来计算总重量
对不起,我的英语不好。问题是选择列表中的所有表达式都是以一次计算所有表达式的方式计算的。这就是为什么需要复制代码。但您可以为该或cte创建子查询,如: 或:
你完全可以使用交叉应用来让事情为你工作。一篇内容丰富的文章:只需使用派生表,如:
select col1, col2
from (select c1 * c2 + c3 as col1,
... as col2
from tablename)
where col1 = ...
你可以用交叉申请
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
你的查询不可靠。检查top 1 stuksweergeven的值1不能保证每次都返回相同的结果。@t-clausen.dk我宁愿称之为非确定性。
select col1, col2
from (select c1 * c2 + c3 as col1,
... as col2
from tablename)
where col1 = ...
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