【问题标题】:SQL Server Stored Procedure - Use Row Count in Select querySQL Server 存储过程 - 在选择查询中使用行计数
【发布时间】:2012-02-26 17:18:59
【问题描述】:

我的存储过程 (SQL Server 2005) 返回一个数据集,其中一个字段取决于查询返回的行数。我可以做一个简化的第一个查询,让我得到@@ROWCOUNT,但在这种情况下,该过程返回两组,这不是我想要的。

我尝试将第一个查询放在 WITH 语句中,但没有找到提取行数并将其放入可以在第二个查询中使用的变量的语法。另一种方法是从第一个查询中获取 @@ROWCOUNT 并告诉该过程只返回第二个查询的结果。

可能有更好的方法可以做到这一点,但我在 SQL 方面的专业知识非常有限......

感谢您的帮助!

【问题讨论】:

    标签: sql-server-2005 stored-procedures rowcount


    【解决方案1】:

    这就是你要找的吗?如果没有,请您更详细地描述您的问题(也许,使用代码 sn-ps)

        alter procedure ComplicatedStoredProcedure as
        begin
            declare @lastQueryRowCount int
    
            -- Storing the number of rows returned by the first query into a variable.
            select @lastQueryRowCount =
                -- First resultset (not seen by caller).
                (select count(*) from A where ID > 100)
    
            -- Second resultset. This will be the actual result returned from the SP.
            select * from B where SomeDependentField > @lastQueryRowCount
        end
    

    【讨论】:

    • 是的,就是这样!非常感谢!带有“select @lastRowCount”的行对我有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    相关资源
    最近更新 更多