如果@@ ROWCOUNT为0存储过程

时间:2018-11-09 11:24:22

标签: tsql

我的存储过程中有以下代码,该代码在用户在HTML页面上输入时执行。

SELECT  a.code, a.name
FROM    table2 b
        INNER JOIN table1 a ON a.id = b.id
WHERE   b.data = @parameter
        AND b.condition = 1
        IF @@ROWCOUNT = 0

    SELECT  a.code, a.name
    FROM    table2_archive b
            INNER JOIN table1 a ON a.id = b.id
    WHERE   b.data = @parameter
            AND b.condition = 1

我想检查一下,如果当前表中存在一个条目,如果不存在,则应该去检查档案并将其返回。 但是,在调用该过程时,它将返回两个表,因此,如果当前表中没有数据,则由于将两个表都返回,因此用户将收到错误消息,但我只希望它返回一个表。我到底在做什么错?

2 个答案:

答案 0 :(得分:1)

您对@@ROWCOUNT的用法有误解,是的

  

returns the number of rows affected by the last statement.

但它不会阻止执行上一个查询。

如果您想使用@@ROWCOUNT,则前一条语句不应具有输出结果(例如,它可以是updateinsert),并且查询可以像这样

--varchar(100) -- because you don't specified the data types

DECLARE @parameter AS VARCHAR(100) = 'xxxx'

DECLARE @tbl1 AS TABLE (code VARCHAR(100), name VARCHAR(100))

INSERT INTO @tbl1 (code, name) -- last statement
SELECT  a.code, a.name
FROM    table2 b
        INNER JOIN table1 a ON a.id = b.id
WHERE   b.data = @parameter
        AND b.condition = 1

-----------------------------------
IF @@ROWCOUNT = 0 -- check if last statement are not produced the rows
--also `IF NOT EXISTS (SELECT * FROM @tbl1)` can be used here, to check if @tbl1 contains a records
    BEGIN
         SELECT  a.code, a.name
         FROM    table2_archive b
                 INNER JOIN table1 a ON a.id = b.id
         WHERE   b.data = @parameter
                 AND b.condition = 1        
    END
ELSE
    SELECT * FROM @tbl1

答案 1 :(得分:0)

如果@@ROWCOUNT0,则存储过程将返回两个结果集-第一个结果集为空,第二个结果集可能具有行。

无论是从table2还是table2_archive中选择查询,都需要重新编写查询以生成单个结果集。

一种方法是,假设table2table2_archive中没有重复的行,是使用公用表表达式和union all,如下所示:

WITH CTE AS
(
    SELECT  data, id
    FROM    table2 
    UNION ALL 
    SELECT  data, id
    FROM    table2_archive 
)

SELECT  a.code, a.name
FROM    cte b
        INNER JOIN table1 a ON a.id = b.id
WHERE   b.data = @parameter
        AND b.condition = 1

如果存在重复的行,则可以应用稍微麻烦一些的解决方案:

WITH CTE AS
(
    SELECT  a.code, a.name
    FROM    table2 b
            INNER JOIN table1 a ON a.id = b.id
    WHERE   b.data = @parameter
            AND b.condition = 1
)

SELECT code, name
FROM CTE
UNION ALL

SELECT  a.code, a.name
FROM    table2_archive b
        INNER JOIN table1 a ON a.id = b.id
WHERE   b.data = @parameter
        AND b.condition = 1
        AND NOT EXISTS (
            SELECT 1 
            FROM CTE
        )