我想做这样的事情:
declare @a int
set @a = 10
select top @a * from tbl
((基本上@a将来自系统设置表)
我可以在没有动态sql字符串的情况下执行此操作吗?
您的代码(几乎)按规定工作。至少在SQL Server 2016下有效,并返回结果:
DECLARE @a int
SET @a = 10
SELECT TOP (@a) [Per_ID]
FROM [tbl_Personen]
您可以使用row_number()
:
select a.*
from (select t.*, row_number() over (order by ?) as seq
from tbl t
) t
where seq <= @a;
但是,如果对()
子句加上括号TOP
,这也将起作用:
declare @a int
set @a = 10
select top (@a) t.*
from tbl t;
Note:如果不使用ORDER BY
子句,则将返回随机行。