select TOP n Rows from table where n is in another

2019-09-03 19:16发布

How can I achieve this without using Dynamic SqlQuery?

I have this Query,

SELECT TOP n FROM mytable WHERE ID = @id

To get the value of n,

SELECT nCOUNT FROM myAnotherTable WHERE ID = @id

Can I use Row_index() for this?

1条回答
Melony?
2楼-- · 2019-09-03 19:38

Try like this....but make sure that your select ncount return single row.....if not than it will select top row ncount

SELECT TOP(SELECT TOP 1 nCOUNT FROM myAnotherTable WHERE ID = @id) * FROM mytable WHERE ID = @id

SqlFiddle: http://www.sqlfiddle.com/#!3/75c76/1

查看更多
登录 后发表回答