Select语句中的SQL @@ RowCount

时间:2016-05-25 15:34:29

标签: sql sql-server

我有一个select语句。我想知道这个select语句是否返回任何行。根据记录计数,我想执行其他一些操作。

我尝试使用@@RowCount来获取计数,但它似乎与select语句无法正常工作。

有关如何使用此建议的任何建议或选择后我可以执行任务的任何其他方式。

select    
    isnull(TotalHoursWorkedAmount, 0) / 26  
from    
    EmployeeStatus ESI
where   
    ESI.EmployeeCode = @employee_id

添加另一部分

if @@ROWCOUNT=0
    SELECT dbo.fxGetAverage(@employee_id)  

2 个答案:

答案 0 :(得分:4)

@@ROWCOUNT 使用select语句。你没有表现出你的尝试,所以我无法说出你做错了什么。

但无论如何,这会以rowcount为例:

select    isnull(TotalHoursWorkedAmount, 0) / 26  
    from    EmployeeStatus ESI
    where   ESI.EmployeeCode = @employee_id

select @@rowcount

或将其存储在变量中:

declare @myCount int

select    isnull(TotalHoursWorkedAmount, 0) / 26  
    from    EmployeeStatus ESI
    where   ESI.EmployeeCode = @employee_id

set @myCount = @@rowcount

正如其他人所说,如果它只是一个真/假问题 - 而不是x yzv如果if exists ( select 1 from EmployeeStatus ESI where ESI.EmployeeCode = @employee_id ) begin print 'do stuff' end 行数 - 然后你最好不要做存在, 除非你真的需要选择 的结果。

public class FinalAccessTest {

  // Some fields
  private int nonfinalfield=4;
  private final int directfinalfield=5;
  private final int constructorfinalfield;

  // element method for the final field with delayed assignment
  private int getConstructorFinalField() { return constructorfinalfield; }

  // Some lambda expressions accessing the fields from above
  private final Supplier<Integer> nonfinalsupp=()->nonfinalfield;  // OK
  private final Supplier<Integer> directfinalsupp=()->directfinalfield;  // OK
  private final Supplier<Integer> constructorfinalsuppA=
    ()->this.constructorfinalfield;  // OK
  private final Supplier<Integer> constructorfinalsuppB=
    ()->getConstructorFinalField();   // OK

  // This one does not compile: The blank final field
  //   constructorfinalfield may not have been initialized
  //private Supplier<Integer> constructorfinalsuppC=()->constructorfinalfield;

  public FinalAccessTest() {
    System.out.println(constructorfinalsuppA.get()); // prints "0"
    System.out.println(constructorfinalsuppB.get()); // prints "0"

    // Does not compile: "may not have been initialized"
    //System.out.println(constructorfinalfield);

    constructorfinalfield=6;
    System.out.println(constructorfinalsuppA.get()); // prints "6"
    System.out.println(constructorfinalsuppB.get()); // prints "6"
    System.out.println(constructorfinalfield); // Compiles and prints "6"

    // now access to a non-final field
    System.out.println(nonfinalsupp.get()); // prints "4"
    nonfinalfield=17;
    System.out.println(nonfinalsupp.get()); // prints "17"

  }

  public static void main(String[] args) { new FinalAccessTest(); }

}

答案 1 :(得分:2)

如果由于某种原因你不能让@@rowcount工作,你可以使用这个查询来检查你是否得到任何结果。使用if语句。

if not exists(select isnull(TotalHoursWorkedAmount, 0) / 26  from EmployeeStatus ESI where ESI.EmployeeCode = @employee_id)
     begin
          SELECT dbo.fxGetAverage(@employee_id) 
     end