SQL 查询TOP子查询

2025-01-05 08:31:43
推荐回答(1个)
回答(1):

可以用变量(把查询的SQL语句存放到字符串变量中,再用exec sp_executesql来执行):

declare @sql nvarchar(1000), @top int
select @top=sort from tx_trainslist where stationname='安康' and trainid='1004/1005'
set @sql = 'select top ' + cast(@top as varchar(10)) + ' sort from tx_trainslist where trainid=''1004/1005'' order by sort'
exec sp_executesql @sql