select TOP n Rows from table where n is in another

2019-09-03 19:01发布

问题:

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:

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