在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
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END