SQLServer Top语句参数化方法

来源:这里教程网 时间:2026-02-28 06:39:16 作者:

在T-Sql中,一般top数据不确定的情况下,都是拼sql,这样无论是效率还是可读性都不好。应该使用下面参数化Top方式

declare @topcount int
set @topcount = 100
select top (@topcount) * from adventureworks.humanresources.employee

如果有like等字句,一定要拼sql的话,也应该使用sp_executesql来执行,示例如下:

declare @topcount int --定义top 数量
set @topcount = 100
declare @title nvarchar(100) --定义like内容
set @title = '%n%'
declare @selectsql nvarchar(max)
set @selectsql = '
select top (@topcountpar) *
from adventureworks.humanresources.employee
where title like @titlepar' --使用参数化的top和like

--使用sp_executesql 来执行,可以提高效率
exec sp_executesql @selectsql,
n'@topcountpar as int,@titlepar as nvarchar(100)',
@topcountpar = @topcount,@titlepar = @title

相关推荐