在SQL存储过程中指定@@ RowCount的正确位置

时间:2015-09-15 13:34:58

标签: sql sql-server stored-procedures

我正在寻找设置@RecordCount = @@ ROWCOUNT的正确位置; 可以只设置一次,还是必须在每次查询后设置它?

我的存储过程如下:

BEGIN
SET NOCOUNT ON;


SELECT *
FROM Table1
WHERE Status = 'A'
AND college = @icollege
AND DeptCode = @idept
AND MajorCode = @imajr;

IF @@ROWCOUNT = 0
BEGIN
    SELECT *
    FROM Table1
    WHERE Status = 'A'
    AND college = @icollege
    AND DeptCode = @idept
    AND MajorCode = '****';

    IF @@ROWCOUNT = 0
    BEGIN
        SELECT *
        FROM Table1
        WHERE Status = 'A'
        AND college = @icollege
        AND DeptCode = '****'
        AND MajorCode = '****';

        SET @RecordCount = @@ROWCOUNT;
    END 

    SET @RecordCount = @@ROWCOUNT;
END

SET @RecordCount = @@ROWCOUNT;
END

1 个答案:

答案 0 :(得分:1)

每个语句 1 都会导致@@ROWCOUNT被设置。这意味着如果你想用一个语句设置的值做多个事情,你需要立即将值捕获到另一个变量中。

所以,我会做类似的事情:

BEGIN
SET NOCOUNT ON;

SELECT *
FROM Table1
WHERE Status = 'A'
AND college = @icollege
AND DeptCode = @idept
AND MajorCode = @imajr;

SET @RecordCount = @@ROWCOUNT;
IF @RecordCount > 0 RETURN

SELECT *
FROM Table1
WHERE Status = 'A'
AND college = @icollege
AND DeptCode = @idept
AND MajorCode = '****';

SET @RecordCount = @@ROWCOUNT;
IF @RecordCount > 0 RETURN

SELECT *
FROM Table1
WHERE Status = 'A'
AND college = @icollege
AND DeptCode = '****'
AND MajorCode = '****';

SET @RecordCount = @@ROWCOUNT;

END
但是,我会注意到这个存储过程最多可以产生3个结果集(第一个或第二个为空)。如果您的调用代码不想处理,那么我们可能需要提出一个应用所有条件的查询,并选择最佳匹配。

1 我可能在这里错了,有一些不起眼的陈述或一组陈述没有。但作为一般规则,对于大多数常见语句,DML,控制流,SET等,都是如此。