欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SQLServer Top语句参数化方法

程序员文章站 2023-11-04 22:31:58
declare @topcount int set @topcount = 100 select top (@topcount) * from adventureworks...

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