关键字附近的语法不正确'如果' SQL

时间:2018-01-29 15:57:19

标签: sql-server tsql

如果运营现金流的平均值<= 0或前3运营现金流的平均值<= 0,我试图得到result5 = 1。错误消息显示关键字附近的语法不正确,如果&#39;。

begin
   declare @OperatingCashflow5 int
   declare @OperatingCashflow3 int
   declare @result5 int

   select @OperatingCashflow5 = AVG(hpd.TotalCashFromOperations)
   from HistoricalFinPerformanceDataStagingGlobal hpd
   where hpd.companyid = @companyid

   select @OperatingCashflow3 = AVG(hpd.TotalCashFromOperations)
   from (
     select top (3) hpd.TotalCashFromOperations 
     from   HistoricalFinPerformanceDataStagingGlobal hpd 
     where hpd.companyid = @companyid
   )

   if @OperatingCashflow5 <= 0 OR @OperatingCashflow3 <= 0 
   begin
      select @result5 = 1
   end
   else
   begin
      select @result5 = 0
   end 
end

1 个答案:

答案 0 :(得分:5)

当您花点时间格式化代码时,更容易看到问题。

在这种情况下,您有一个嵌套的SELECT语句,嵌套的select必须有一个别名。您只需在结束括号后添加一个字母(任何字母):

function getDepth(object) {
    return 1 + Math.max(0, ...(object.children || []).map(getDepth));
}

var test = { name: 'item 1', children: [{ name: 'level 1 item', children: [{ name: 'level 2 item' }, { name: 'second level 2 item', children: [{ name: 'level 3 item' }] }] }] },
    depth = getDepth(test) - 1; // zero based

console.log(depth);

我怀疑该特定选择查询还存在其他问题。