sql - 稍后在查询中使用 'AS ColumnName' 的值

标签 sql sql-server stored-procedures

我正在创建一个存储过程,我需要使用之前设置的值。我不太擅长解释这一点,所以我将使用一个例子:

  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。

抱歉我的英语不好。

最佳答案

问题是,SELECT 列表中的所有表达式都以一次性 方式求值。这就是为什么您需要复制代码。但是您可以为其创建子查询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

关于sql - 稍后在查询中使用 'AS ColumnName' 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30030370/

相关文章:

mysql SELECT 单个表中每个类别的最佳选择

SQL:喜欢vs包含-不同的结果

php - 在 Woocommerce 中获取具有特定产品属性的产品购买总数

sql - 无法使用创建的新用户登录到 sql server

c# - 如何从 json 数组中读取每个数据并将其分配给 SQL Server IN 子句

php - 使用 PDO 调用带有 Out 参数的存储过程

sql - 在表中插入一行并将其范围标识存储在存储过程的变量中

mysql - Excel 字符串中的多个单词替换

c# - SqlConnection 在获取 ConnectionString 时未设置密码

c# - 使用Oracle存储过程在多个表中插入数据