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

0 t-sql sql-server

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

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
Run Code Online (Sandbox Code Playgroud)

Joe*_*orn 5

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

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

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
   ) hpd -- <<<< Need a name here

   if @OperatingCashflow5 <= 0 OR @OperatingCashflow3 <= 0 
   begin
      select @result5 = 1
   end
   else
   begin
      select @result5 = 0
   end 
end
Run Code Online (Sandbox Code Playgroud)

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