简体   繁体   English

在 SQL 存储过程中分配 @@RowCount 的正确位置

[英]Correct spot to assign @@RowCount in SQL stored procedure

I am looking for the correct spot to set my @RecordCount = @@ROWCOUNT;我正在寻找正确的位置来设置我的@RecordCount = @@ROWCOUNT; Is it possible to just set it once or is it necessary to set it after each query?是可以只设置一次还是每次查询后都需要设置?

My stored procedure is as follows:我的存储过程如下:

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

Every statement 1 causes @@ROWCOUNT to be set.每个语句1都会导致设置@@ROWCOUNT This means that if you want to do multiple things with the value set by one statement, you need to capture the value immediately into another variable.这意味着如果你想用一个语句设置的值做多件事,你需要立即将该值捕获到另一个变量中。

So, I'd do something like:所以,我会做这样的事情:

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

I would, though, also note that this stored procedure may produce up to 3 result sets (with the first 1 or 2 being empty).不过,我还要注意,此存储过程最多可以生成 3 个结果集(前 1 或 2 个为空)。 If your calling code doesn't want to deal with that then we may need to come up with a single query that applies all of the criteria, and selects for the best matches.如果您的调用代码不想处理这个问题,那么我们可能需要提出一个应用所有条件的查询,并选择最佳匹配。


1 I'm probably wrong here and there's some obscure statement or set of statements that do not. 1我可能在这里错了,并且有一些晦涩的陈述或一组陈述没有。 But as a general rule and for most common statements, DML, control flow, SET , etc, it's true.但作为一般规则,对于最常见的语句、DML、控制流、 SET等,这是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM