首頁  >  文章  >  資料庫  >  SQLServer Top语句参数化方法

SQLServer Top语句参数化方法

WBOY
WBOY原創
2016-06-07 17:58:371031瀏覽

在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

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn