简介

rowcount和@@rowcount是数据库中两特殊变量。

详解

rowcount

rowcount的作用就是用来限定后面的sql在返回指定的行数之后便停止处理,注意rowcount设置会在整个会话中有效,且对修改(update),删除(delete)一样有效。
例子:

set rowcount 10;
select * from table_A;
go
select * from table_B;

--分别查询表table_A和表table_B和前十条数据。
--类似select top 10 * from table;操作

要取消set rowcount的限定,只要设置 set rowcount 0 就可以。

@@Rowcount

@@Rowcount主要是返回上次sql语句所影响的数据行数,注意删除(delete),修改(update),新增(insert)等语句也会返回值。
例子:

select * from table_A where id='a';
select @@Rowcount;

--返回表table_A数据的行数
--如果是空表,则@@Rowcount=0

应用场景

rowcount应用场景

select top 后面不能加参数,只能使用一个具体的int类型的数字。如果想实现top后面跟参数的功能,就只能使用exec执行。但是性能很差,可以使用rowcount来实现,如下:

declare @n int
set @n=10
set rowcount @n
select * from table_A

@@rowcount应用场景

可以使用@@rowcount来作递归或循环,例如:

declare @n int
set @n=2
select * from table_A where name like left('%tom',@n)

while @@rowcount=0
begin
set @n=@n+1
select * from table_A where like left('%tom',@n)
end